Insert document in MONGO DB
Insert single document
db.collection.insertOne({ name:"UPS", price:4500, sale_price:2300 });
Insert multiple documents
db.collection.insertOne([ { name:"Printer", price:9000, sale_price:8000 }, { name:"Mobile", price: 9500, sale_price: 7500 } ]);
Find/Select documents in MONGO DB
Syntax
db.collection.findOne(query, projection)
- query define condition or critearia
- projection define the which field will return
Fetch first document with all the fields
db.collection.findOne()
or
db.collection.findOne({})
Fetch match document with specific fields
db.collection.findOne({name:"ups"},{name:1, sale_price:1})
Note
- When we want to include field in results we will use 1
- or when we do not want to include field in results we will use 0
syntax:
db.collection.find(filter, projection);
Delete documents
Syntax
db.collection.deleteOne(filter);
Delete single document
db.collection.deleteOne({_id:2});
Delete multiple documents
db.collection.deleteMany({name:"UPS"});
Update documents in Mongo DB
Syntax
db.collection.updateOne(filter, update);
db.collection.updateMany(filter, update);
db.collection.updateOne(
{_id:2},
{
$set:{
price: 5000
}
});