Implement multiple conditions in MongoDB?

MongoDBDatabaseBig Data Analytics

Let us first create a collection with documents −

> db.multipleConditionDemo.insertOne({"_id":1,"Name":"John"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.multipleConditionDemo.insertOne({"_id":2,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.multipleConditionDemo.insertOne({"_id":3,"Name":"Sam"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.multipleConditionDemo.insertOne({"_id":4,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 4 }

Following is the query to display all documents from a collection with the help of find() method −

> db.multipleConditionDemo.find().pretty();

This will produce the following output −

{ "_id" : 1, "Name" : "John" }
{ "_id" : 2, "Name" : "Carol" }
{ "_id" : 3, "Name" : "Sam" }
{ "_id" : 4, "Name" : "David" }

Following is the query to implement multiple conditions in WHERE clause −

> db.multipleConditionDemo.remove({ $or: [ { _id: 2 }, { _id: 3 } ] });
WriteResult({ "nRemoved" : 2 })

Let us check the documents from the above collection once again −

> db.multipleConditionDemo.find().pretty();

This will produce the following output −

{ "_id" : 1, "Name" : "John" }
{ "_id" : 4, "Name" : "David" }
raja
Published on 22-May-2019 11:25:47
Advertisements