4

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"
                    }
                ]
            }
        ]
    }
}

1 Answer 1

4

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", []] }
        }
      }
    }
  }}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.