Implement array match in MongoDB?


Use $all for array match. 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.demo668.createIndex({"ListOfSubject":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo668.insert({"ListOfSubject":["MySQL","Java","C"]});
WriteResult({ "nInserted" : 1 })
> db.demo668.insert({"ListOfSubject":["MongoDB","Python","C++"]});
WriteResult({ "nInserted" : 1 })
> db.demo668.insert({"ListOfSubject":["C#","Spring","Hibernate","MongoDB"]});
WriteResult({ "nInserted" : 1 })

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

> db.demo668.find();

This will produce the following output −

{ "_id" : ObjectId("5ea311df04263e90dac943d6"), "ListOfSubject" : [ "MySQL", "Java", "C" ] }
{ "_id" : ObjectId("5ea311e004263e90dac943d7"), "ListOfSubject" : [ "MongoDB", "Python", "C++" ] }
{ "_id" : ObjectId("5ea311e104263e90dac943d8"), "ListOfSubject" : [ "C#", "Spring", "Hibernate", "MongoDB" ] }

Following is the query for array match −

> db.demo668.find({"ListOfSubject":{ $all:["MongoDB","C++"]}});

This will produce the following output −

{ "_id" : ObjectId("5ea311e004263e90dac943d7"), "ListOfSubject" : [ "MongoDB", "Python", "C++" ] }

Updated on: 13-May-2020

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements