MongoDB query for documents matching array, irrespective of elements order


For this, use $all in MongoDB. The $all operator in MongoDB selects the documents where the value of a field is an array that contains all the specified elements.

Let us first create a collection with documents −

> db.demo370.insertOne(
...    {
...       "Name" : "Chris",
...       "details" : [
...          {
...             "Subject" : "MySQL",
...             "CountryName" : "US"
...          },
...          {
...             "Subject" : "MongoDB",
...             "CountryName" : "UK"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e9892ae06a1609a00af0")
}
> db.demo370.insertOne(
...    {
...       "Name" : "David",
...       "details" : [
...          {
               "Subject" : "Java",
...             "CountryName" : "AUS"
...          },
...          {
...             "Subject" : "Spring",
...             "CountryName" : "UK"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e9972ae06a1609a00af1")
}

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

> db.demo370.find();

This will produce the following output −

{
   "_id" : ObjectId("5e57e9892ae06a1609a00af0"), "Name" : "Chris", "details" : [
      { "Subject" : "MySQL", "CountryName" : "US" },
      { "Subject" : "MongoDB", "CountryName" : "UK" }
   ]
}
{
   "_id" : ObjectId("5e57e9972ae06a1609a00af1"), "Name" : "David", "details" : [
      { "Subject" : "Java", "CountryName" : "AUS" },
      { "Subject" : "Spring", "CountryName" : "UK" }
   ]
}

Following is the query for documents matching array, irrespective of elements order −

> db.demo370.find({
...    details: {$all: [
...    {Subject:"MySQL","CountryName" : "US"},
...    {Subject:"MongoDB", "CountryName" : "UK"}
... ]}})

This will produce the following output −

{
   "_id" : ObjectId("5e57e9892ae06a1609a00af0"), "Name" : "Chris", "details" : [
      { "Subject" : "MySQL", "CountryName" : "US" },
      { "Subject" : "MongoDB", "CountryName" : "UK" }
   ] 
}

Updated on: 02-Apr-2020

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements