Show All Created Databases
show dbs
Starte using the database named dbname
use dbname
Show a collections inside a database
show collections
Delete/Drop a database
db.dropDatabase();
Create database if not exist and start using it
use dbname
Get the current databse
db;
Create a collection named posts
db.createCollection("posts");
Insert a post into posts
collection
db.posts.insert({ name: "Shehan", age: 24 });
Insert many posts into posts
collection
db.posts.insertMany([{}, {}, {}]);
Get all the posts
db.posts.find();
Show all posts in a pretty way
db.posts.find().pretty();
Sort all posts based on title to Ascending order
db.posts.sort({ title: 1 }).pretty();
Count the number os posts
db.posts.find({ category: "news" }).count();
Get only 2 posts (Limit the number of posts)
db.posts
.find()
.limit(2)
.pretty();
#Get only 2 posts from the sorted posts
db.posts
.find()
.sort({ title: -1 })
.limit(2)
.pretty();
Print all the names of posts
db.posts.find().forEach(function(post) {
print("Post" + post.name);
});
Get only one post from 'news' category
db.posts.findOne({ category: "news" });
Update a post, if not found, insert it
db.posts.update(
{ name: "Shehan" },
{ name: "Shay", age: 24 },
{ upsert: true }
);
Only update the specific part
db.posts.update({ name: "Shehan" }, { $set: { name: "Morgan", isMale: true } });
Increase age by 2
db.posts.update({ name: "Shehan" }, { $inc: { age: 2 } });
Rename 'age' to 'years'
db.posts.update({ name: "Shehan" }, { $rename: { age: years } });
Remove an instance
db.posts.remove({ name: "Shehan" });
Add sub documents
db.posts.update({ name: "Shehan" }, { $set: { skills: ["JavaScript"] } });
Find a document by sub document
db.users.find({ comments: { $elemMatch: { name: "Haily" } } }).pretty();
Creating an index
db.users.createIndex({ username: "text" });
Searching with Index
db.users.find({ $text: { $search: '"Moriah"' } }).pretty();
Greater than
db.users.find({ id: { $gt: 9 } }).pretty();
Greater than or Equal
db.users.find({ id: { $gte: 9 } }).pretty();
Lesser than
db.users.find({ id: { $lt: 9 } }).pretty();
Lesser than or Equal
db.users.find({ id: { $lte: 9 } }).pretty();