Home > Net >  Projection on nested object mongodb find query
Projection on nested object mongodb find query

Time:01-06

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 below find query I tried find query i.e.

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

I am getting error, regarding that can not do inclusion on field meta.region in exclusion projection. Is there any other way to achieve this problem. I want the output,

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

This is the mongoplayground

CodePudding user response:

Remove projection (wrapping) level.

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

Sample Mongo Playground

  •  Tags:  
  • Related