MongoDB query to limit subdocuments having the given fields of the 'projection'


For this, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo285.insertOne(
...   {... details : [
...      {
...         Name : "Chris"
...      },
...      {
...         Name2: "Bob"
...      },
...      {
...         Name: "Mike"
...      }
...   ]
...   }
...)
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4abffef49383b52759cbb9")
}

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

> db.demo285.find();

This will produce the following output −

{ "_id" : ObjectId("5e4abffef49383b52759cbb9"), "details" : [ { "Name" : "Chris" }, { "Name2" : "Bob" }, { "Name" : "Mike" } ] }

Following is the query to limit subdocuments having the given fields of the `projection` −

> db.demo285.aggregate(
...   [
...      { $match:
...         {'details.Name' :
...            { $exists: 1 }
...         }
...      },
...         { $unwind: "$details" },
...         { $match:
...            {'details.Name' :
...            { $exists: 1 }
...         }
...      },
...      { $project: { Name: "$details.Name", _id: 0 } }
...   ])

This will produce the following output −

{ "Name" : "Chris" }
{ "Name" : "Mike" }

Updated on: 31-Mar-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements