MongoDB – CRUD
(Create, Read, Update, Delete)
Before moving further with CRUD operation in mongodb.You can refer the below table of comparison of MongoDb vs Any relational database (Oracle Mysql,DB2 etc.)
So as you can see in above figure.in Mongodb Sql table are referred as Collections.
1.Create
MongoDB db.createCollection(name, options) is used to create collection.
Syntax:
Basic syntax of createCollection() command is as follows
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection which is optional.
Examples:
Basic syntax of createCollection() method without options is as follows
use test
switched to db test
db.createCollection("mycollection")
{ "ok" : 1 }
You can check the created collection by using the command show collections
show collections
mycollection
system.indexes
In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document(Row in sql).
db.tutorialspoint.insert({"name" : "tutorialspoint"})
show collections
mycollection
system.indexes
tutorialspoint
2.Read
• findOne
• find
Syntax:
• db.collection_name.findOne( <condition>, <fileds to fetch> );
• db.collection_name.find( <condition>, <fileds to fetch> );
Example:
> db.test.insert({"name":"Rahul"});
WriteResult({ "nInserted" : 1 })
> db.test.insert({"name":"Rahul_2"});
WriteResult({ "nInserted" : 1 })
SQL : select * from (Select * from test where name ="Rahul") where rownum=1;
Mongo : db.test.findOne({"name":"Rahul"});
{ "_id" : ObjectId("57386733212b0a31faedc82b"), "name" : "Rahul" }
SQL : Select * from test where name ="Rahul";
Mongo: db.test.find({"name":"Rahul"});
{ "_id" : ObjectId("57386733212b0a31faedc82b"), "name" : "Rahul" }
SQL : Select * from test
Mongo: db.test.find();
{ "_id" : ObjectId("57386733212b0a31faedc82b"), "name" : "Rahul" }
{ "_id" : ObjectId("57386739212b0a31faedc82c"), "name" : "Rahul_2" }
Incase we need specific field from collections i.e fetch selected columns of table we can below commands.
db.inventory.insert(
{
item: "ABC1",
details: {
model: "14Q3",
manufacturer: "XYZ Company"
},
stock: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ],
category: "clothing"
}
)
WriteResult({ "nInserted" : 1 })
SQL : Select item from inventory;
Mongo : db.inventory.find({},{item:1});
{ "_id" : ObjectId("57386b1befcf19a06c49f0a0"), "item" : "ABC1" }
Incase you want to remove _id field we can use below command.
Mongo: db.inventory.find({},{item:1, _id:0});
Result : { "item" : "ABC1" }