MongoDB projection on specific nested properties?


For projection on specific nested properties, use aggregate() in MongoDB. Let us first create a collection with documents −

> db.demo379.insertOne(
...    {
...       "details1" : {
...          "details2" : {
...             "details3" : {
...                "10" : "John",
...                "50" : "Chris",
...                "40" : "David",
...                "30":"Mike"
...             }
...          }
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5a94f82ae06a1609a00b10")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e5a94f82ae06a1609a00b10"),
   "details1" : {
      "details2" : {
         "details3" : {
            "10" : "John",
            "30" : "Mike",
            "40" : "David",
            "50" : "Chris"
         }
      }
   }
}

Following is the query for projection on specific nested properties −

> db.demo379.aggregate([
...    { "$addFields": {
...       "details1.details2.details3": {
...          "$arrayToObject": {
...             "$filter": {
...                "input": { "$objectToArray": "$details1.details2.details3" },
...                "as": "out",
...                "cond": {
...                   "$and": [
...                      { "$gte": ["$$out.k", "35"] },
...                      { "$lte": ["$$out.k", "60"] },
...                   ]
...                }
...             }
...          }
...       }
...    } }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e5a94f82ae06a1609a00b10"), "details1" : { "details2" : { "details3" : { "40" : "David", "50" : "Chris" } } } }

Updated on: 02-Apr-2020

853 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements