MongoDB query to get specific list of names from documents where the value of a field is an array

MongoDBDatabaseBig Data Analytics

For this, use $all. The $all operator selects the documents where the value of a field is an array that contains all the specified elements. Let us create a collection with documents −

> db.demo642.insertOne(
...    {
...       _id:1,
...       ListOfNames:["Robert","John"]
...    }
... );
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo642.insertOne( { _id:2, ListOfNames:["Robert","Chris"] } );
{ "acknowledged" : true, "insertedId" : 2 }

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

> db.demo642.find();

This will produce the following output −

{ "_id" : 1, "ListOfNames" : [ "Robert", "John" ] }
{ "_id" : 2, "ListOfNames" : [ "Robert", "Chris" ] }

Following is the query to get specific list of names from documents where the value of a field is an array −

> db.demo642.find({ListOfNames: {
...    $all: [ "Chris", "Robert" ]
... }})

This will produce the following output −

{ "_id" : 2, "ListOfNames" : [ "Robert", "Chris" ] }
raja
Published on 12-May-2020 11:50:32
Advertisements