MongoDB query to find and return subdocument with criteria?

MongoDBDatabaseBig Data Analytics

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" }
   ] 
}
raja
Published on 02-Apr-2020 07:38:44
Advertisements