How to select objects where an array contains only a specific field in MongoDB?


Let us first create a collection with documents −

> db.arrayContainOnlySpecificFieldDemo.insertOne(
...    {
...       "StudentName":"John",
...       "StudentAge":21,
...       "StudentTechnicalSubject":["C","Java","MongoDB"]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc4921dac184d684e3fa26a")
}
> db.arrayContainOnlySpecificFieldDemo.insertOne( { "StudentName":"Carol",
"StudentAge":23, "StudentTechnicalSubject":["MongoDB"] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc49237ac184d684e3fa26b")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cc4921dac184d684e3fa26a"),
   "StudentName" : "John",
   "StudentAge" : 21,
   "StudentTechnicalSubject" : [
      "C",
      "Java",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5cc49237ac184d684e3fa26b"),
   "StudentName" : "Carol",
   "StudentAge" : 23,
   "StudentTechnicalSubject" : [
      "MongoDB"
   ]
}

Following is the query to select objects where an array contains only a specific field −

> db.arrayContainOnlySpecificFieldDemo.find({"StudentTechnicalSubject":[
"MongoDB"]}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc49237ac184d684e3fa26b"),
   "StudentName" : "Carol",
   "StudentAge" : 23,
   "StudentTechnicalSubject" : [
      "MongoDB"
   ]
}

Updated on: 30-Jul-2019

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements