MongoDB query to find and return subdocument with criteria?


Let us create a collection with documents −

> db.demo345.insertOne({
...    "UserName" : "Robert",
...       "UserDetails" : [
...          {
...             "isMarried" : false,
...             "CountryName":"US"
...
...          },
...          {
...             "isMarried" : true,
...             "CountryName":"UK"
...
...          },
...          {
...             "isMarried" : false,
...             "CountryName":"AUS"
...
...          }
...       ]
...    }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5404fdf8647eb59e5620ac")
}

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

> db.demo345.find();

This will produce the following output −

{
   "_id" : ObjectId("5e5404fdf8647eb59e5620ac"), "UserName" : "Robert", "UserDetails" : [
      { "isMarried" : false, "CountryName" : "US" },
      { "isMarried" : true, "CountryName" : "UK" },
      { "isMarried" : false, "CountryName" : "AUS" }
   ]
}

Following is the query to find and then return subdocument with criteria −

> db.demo345.aggregate([
...    {
...       $match: { UserName: "Robert" }
...    },
...    {
...       $addFields: {
...          UserDetails: {
...             $filter: {
...                input: "$UserDetails",
...                cond: {
...                   $eq: [ "$$this.isMarried", true ]
...                }
...             }
...          }
...       }
...    }
... ])

This will produce the following output −

{
   "_id" : ObjectId("5e5404fdf8647eb59e5620ac"), "UserName" : "Robert", "UserDetails" : [
      { "isMarried" : true, "CountryName" : "UK" }
   ] 
}

Updated on: 02-Apr-2020

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements