MongoDB Query to implement $in in array

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo520.insertOne({"ListOfName":["John","Bob"]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e899fb4b3fbf26334ef6114")
}
> db.demo520.insertOne({"ListOfName":["Chris","David"]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e899fbfb3fbf26334ef6115")
}
> db.demo520.insertOne({"ListOfName":["Mike","Bob"]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e899fc7b3fbf26334ef6116")
}

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

> db.demo520.find();

This will produce the following output −

{ "_id" : ObjectId("5e899fb4b3fbf26334ef6114"), "ListOfName" : [ "John", "Bob" ] }
{ "_id" : ObjectId("5e899fbfb3fbf26334ef6115"), "ListOfName" : [ "Chris", "David" ] }
{ "_id" : ObjectId("5e899fc7b3fbf26334ef6116"), "ListOfName" : [ "Mike", "Bob" ] }

Here is the query to implement $in array>

> db.demo520.find({"ListOfName":{$in:["Bob","Mike"]}});

This will produce the following output −

{ "_id" : ObjectId("5e899fb4b3fbf26334ef6114"), "ListOfName" : [ "John", "Bob" ] }
{ "_id" : ObjectId("5e899fc7b3fbf26334ef6116"), "ListOfName" : [ "Mike", "Bob" ] }
raja
Published on 13-May-2020 10:42:34
Advertisements