mongodbmongodb-queryfindprojectionnested-object

MongoDB - Projection on nested object in find query


How to get the nested object in projection in MongoDB find query?

[
  {
    "apikey": 1,
    "meta": {
      "region": {
        "country": "India",
        "city": "bangalore",
        "pincode": 560067
      },
      "address": {
        "houseNo": "G/C 42 Whitefield boulavourd",
        "landmark": "whitefield boulavourd"
      }
    }
  },
  {
    "apikey": 2,
    "meta": {
      "region": {
        "country": "Germaany",
        "city": "Munich",
        "pincode": 80297
      },
      "address": {
        "houseNo": "Zweibrückenstraße 12",
        "landmark": "Zweibrückenstraße 12"
      }
    }
  }
]

I was trying to fetch the region of apikey: "2". I tried the below find query:

db.collection.find({
    "apikey": "2"
  },
  {
    "projection": {
      "_id": 0,
      "apikey": 1,
      "meta.region": 1
    }
})

I am getting an error, regarding that cannot do the inclusion of the field meta.region in the exclusion projection. Is there any other way to solve this problem? I want the output:

[
    {
        "apikey":2,
        "region": {
            "country": "Germaany",
            "city": "Munich",
            "pincode": 80297
        }
    }
]

This is the MongoPlayground


Solution

  • Remove projection (wrapping) level.

    db.collection.find({
      apikey: 2
    },
    {
      "_id": 1,
      "apikey": "$apikey",
      "region": "$meta.region"
    })
    

    Sample Mongo Playground