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



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" ] }
Updated on: 2020-05-12T08:24:42+05:30

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements