krsna
krsna

Reputation: 4333

MongoDB: Get only specific fields in nested array documents

I'm trying to project the values from nested array documents which are in the below format. What I expect is to display only the specValue of the specific specType selected in the find query.

{
    "carId": "345677"
    "car" : {
        "model" : [ 
            {
                "specs" : [ 
                    {
                        "specType": "SEDAN"
                        "specValue" : "1"
                    }, 
                    {
                        "specType": "BR_INC"
                        "specValue" : "yes"
                    }, 
                    {
                        "specType": "PLAN"
                        "specValue" : "gold"
                    }
                ]
            }
        ]
    }
}

This is what I have tried.

db.cars.find({carId:'345677','car.model.specs.specType':'SEDAN'},{'car.model.specs.specValue':1})

This approach gives me the all the specValues instead like below.

{
    "carId": "345677"
    "car" : {
        "model" : [ 
            {
                "specs" : [ 
                    {
                        "specValue" : "1"
                    }, 
                    {
                        "specValue" : "yes"
                    }, 
                    {
                        "specValue" : "gold"
                    }
                ]
            }
        ]
    }
}

How do I make this right to get in the right format like this. Could anyone please help.

{
    "carId": "345677"
    "car" : {
        "model" : [ 
            {
                "specs" : [ 
                    {
                        "specType": "SEDAN"
                        "specValue" : "1"
                    }
                ]
            }
        ]
    }
}

Upvotes: 4

Views: 1041

Answers (1)

Ashh
Ashh

Reputation: 46441

You can use below aggregation

db.collection.aggregate([
  { "$project": {
    "car": {
      "model": {
        "$filter": {
          "input": {
            "$map": {
              "input": "$car.model",
              "in": {
                "specs": {
                  "$filter": {
                    "input": "$$this.specs",
                    "cond": { "$eq": ["$$this.specType", "SEDAN"] }
                  }
                }
              }
            }
          },
          "cond": { "$ne": ["$$this.specs", []] }
        }
      }
    }
  }}
])

Upvotes: 4

Related Questions