Matching an array field that contains any combination of the provided array in MongoDB?


Use $nin operator along with $elemMatch and $not for this. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.combinationOfArrayDemo.insertOne({"StudentName":"Larry","StudentAge":21,"StudentFavouriteTechnicalSubject":["C","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f77cc8d10a061296a3c58")
}
> db.combinationOfArrayDemo.insertOne({"StudentName":"Mike","StudentAge":23,"StudentFavouriteTechnicalSubject":["C++","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f77dc8d10a061296a3c59")
}
> db.combinationOfArrayDemo.insertOne({"StudentName":"David","StudentAge":22,"StudentFavouriteTechnicalSubject":["Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f77f48d10a061296a3c5a")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.combinationOfArrayDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c7f77cc8d10a061296a3c58"),
   "StudentName" : "Larry",
   "StudentAge" : 21,
   "StudentFavouriteTechnicalSubject" : [
      "C",
      "Java"
   ]
}
{
   "_id" : ObjectId("5c7f77dc8d10a061296a3c59"),
   "StudentName" : "Mike",
   "StudentAge" : 23,
   "StudentFavouriteTechnicalSubject" : [
      "C++",
      "Java"
   ]
}
{
   "_id" : ObjectId("5c7f77f48d10a061296a3c5a"),
   "StudentName" : "David",
   "StudentAge" : 22,
   "StudentFavouriteTechnicalSubject" : [
      "Java"
   ]
}

Here is the query for matching an array field that contains any combination of the provided array in MongoDB −

> db.combinationOfArrayDemo.find({StudentFavouriteTechnicalSubject: {$not: {$elemMatch:
{$nin: ['C++', 'Java']}}}}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c7f77dc8d10a061296a3c59"),
   "StudentName" : "Mike",
   "StudentAge" : 23,
   "StudentFavouriteTechnicalSubject" : [
      "C++",
      "Java"
   ]
}
{
   "_id" : ObjectId("5c7f77f48d10a061296a3c5a"),
   "StudentName" : "David",
   "StudentAge" : 22,
   "StudentFavouriteTechnicalSubject" : [
      "Java"
   ]
}

Updated on: 30-Jul-2019

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements