Filter documents in MongoDB if all keys exist as fields?


For this, use $all, that would find documents containing all of the elements in an array like "keys". Let us first create a collection with documents −

> db.demo17.insertOne({"ListOfSubject":["MySQL","MongoDB","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e13847255d0fc6657d21f0a")
}
> db.demo17.insertOne({"ListOfSubject":["C","Python","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e13847e55d0fc6657d21f0b")
}
> db.demo17.insertOne({"ListOfSubject":["C++","MongoDB","PL/SQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e13849255d0fc6657d21f0c")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.demo17.find();

This will produce the following output −

{ "_id" : ObjectId("5e13847255d0fc6657d21f0a"), "ListOfSubject" : [ "MySQL", "MongoDB", "Java" ] }
{ "_id" : ObjectId("5e13847e55d0fc6657d21f0b"), "ListOfSubject" : [ "C", "Python", "Java" ] }
{ "_id" : ObjectId("5e13849255d0fc6657d21f0c"), "ListOfSubject" : [ "C++", "MongoDB", "PL/SQL" ] }

Here is the query to filter documents if all keys exist as fields −

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

This will produce the following output −

{ "_id" : ObjectId("5e13849255d0fc6657d21f0c"), "ListOfSubject" : [ "C++", "MongoDB",
"PL/SQL" ] }

Updated on: 01-Apr-2020

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements