MongoDB - How can I see if all elements of a field are contained in a superset?


For all elements of a field in MongoDB, use find() and in that, use $elemMatch. The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

Let us create a collection with documents −

> db.demo624.insertOne({"ListOfName":["John","Chris","David","Bob"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ab3ff6c954c74be91e6a5")
}
> db.demo624.insertOne({"ListOfName":["John","Chris"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ab4026c954c74be91e6a6")
}
> db.demo624.insertOne({"ListOfName":["John","Chris","Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ab4076c954c74be91e6a7")
}
> db.demo624.insertOne({"ListOfName":["John","Chris","Bob"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ab40e6c954c74be91e6a8")
}
> db.demo624.insertOne({"ListOfName":["John","Chris","Mike","Robert"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ab4186c954c74be91e6a9")
}

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

> db.demo624.find();

This will produce the following output −

{ "_id" : ObjectId("5e9ab3ff6c954c74be91e6a5"), "ListOfName" : [ "John", "Chris", "David", "Bob" ] }
{ "_id" : ObjectId("5e9ab4026c954c74be91e6a6"), "ListOfName" : [ "John", "Chris" ] }
{ "_id" : ObjectId("5e9ab4076c954c74be91e6a7"), "ListOfName" : [ "John", "Chris", "Carol" ] }
{ "_id" : ObjectId("5e9ab40e6c954c74be91e6a8"), "ListOfName" : [ "John", "Chris", "Bob" ] }
{ "_id" : ObjectId("5e9ab4186c954c74be91e6a9"), "ListOfName" : [ "John", "Chris", "Mike", "Robert" ] }

Following is the query to see if all elements of a field are contained in a superset −

> db.demo624.find({"ListOfName":{$not:{$elemMatch:{$nin:["John", "Chris", "David", "Bob"]}}}});

This will produce the following output −

{ "_id" : ObjectId("5e9ab3ff6c954c74be91e6a5"), "ListOfName" : [ "John", "Chris", "David", "Bob" ] }
{ "_id" : ObjectId("5e9ab4026c954c74be91e6a6"), "ListOfName" : [ "John", "Chris" ] }
{ "_id" : ObjectId("5e9ab40e6c954c74be91e6a8"), "ListOfName" : [ "John", "Chris", "Bob" ] }

Updated on: 12-May-2020

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements