To search for multiple documents in MongoDB, use $in. Let us create a collection with documents −
> db.demo161.insertOne({"ClientId":101,"ClientName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3577cafdf09dd6d0853a09")
}
> db.demo161.insertOne({"ClientId":102,"ClientName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3577d0fdf09dd6d0853a0a")
}
> db.demo161.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3577dffdf09dd6d0853a0b")
}
> db.demo161.insertOne({"ClientId":104,"ClientName":"Carol","ClientAge":31});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3577eefdf09dd6d0853a0c")
}Display all documents from a collection with the help of find() method −
> db.demo161.find();
This will produce the following output −
{ "_id" : ObjectId("5e3577cafdf09dd6d0853a09"), "ClientId" : 101, "ClientName" : "Chris" }
{ "_id" : ObjectId("5e3577d0fdf09dd6d0853a0a"), "ClientId" : 102, "ClientName" : "David" }
{ "_id" : ObjectId("5e3577dffdf09dd6d0853a0b"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
{ "_id" : ObjectId("5e3577eefdf09dd6d0853a0c"), "ClientId" : 104, "ClientName" : "Carol", "ClientAge" : 31 }Following is the query to search for multiple documents in MongoDB −
> db.demo161.find({ClientId:{$in:[101,103,104]}});This will produce the following output −
{ "_id" : ObjectId("5e3577cafdf09dd6d0853a09"), "ClientId" : 101, "ClientName" : "Chris" }
{ "_id" : ObjectId("5e3577dffdf09dd6d0853a0b"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
{ "_id" : ObjectId("5e3577eefdf09dd6d0853a0c"), "ClientId" : 104, "ClientName" : "Carol", "ClientAge" : 31 }