MongoDB compound conditions to fetch documents?

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo714.insertOne({FirstName:"Chris",LastName:"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea9a2da85324c2c98cc4c2b")
}
> db.demo714.insertOne({FirstName:"Adam",LastName:"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea9a2e585324c2c98cc4c2c")
}
> db.demo714.insertOne({FirstName:"David",LastName:"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea9a2ed85324c2c98cc4c2d")
}
> db.demo714.insertOne({FirstName:"John",LastName:"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea9a2f785324c2c98cc4c2e")
}

Display all documents from a collection with the help of find() method −

> db.demo714.find();

This will produce the following output −

{ "_id" : ObjectId("5ea9a2da85324c2c98cc4c2b"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea9a2e585324c2c98cc4c2c"), "FirstName" : "Adam", "LastName" : "Smith" }
{ "_id" : ObjectId("5ea9a2ed85324c2c98cc4c2d"), "FirstName" : "David", "LastName" : "Miller" }
{ "_id" : ObjectId("5ea9a2f785324c2c98cc4c2e"), "FirstName" : "John", "LastName" : "Doe" }

Here is the query to compound conditions −

> db.demo714.find({"LastName":{$in:["Miller","Brown"]}});

This will produce the following output −

{ "_id" : ObjectId("5ea9a2da85324c2c98cc4c2b"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea9a2ed85324c2c98cc4c2d"), "FirstName" : "David", "LastName" : "Miller" }
raja
Published on 14-May-2020 10:09:53
Advertisements