arraysmongodbmeteormongo-shellminimongo

MongoDB Querying Nested Arrays


I'm having some trouble with querying a Mongo Collection.

I have a Collection like this:

{
"_id" : "555bd34329de3cf232434ef2",
"cars" : [ 
    {
        "0" : {
            "parts" : [ 
                {
                    "name" : "x1",
                    "price" : 12
                },
                {
                    "name" : "x2",
                    "price" : 14
                }
            ]
        },
        "1" : {
            "parts" : [ 
                {
                    "name" : "y1",
                    "price" : 8
                },
                {
                    "name" : "y2",
                    "price" : 12
                }
            ]
        } 
    }
]
}

I'd like to return just the following:

"parts" : [ 
    {
        "name" : "x1",
        "price" : 12
    },
    {
        "name" : "x2",
        "price" : 14
    }
]

In other words, I need to figure out how to query the Collection by two parameters at the same time:

Does anyone know how to do this kind of nested query?


Solution

  • Assuming a document structure like this:

    {
        "_id" : ObjectId("555bd34329de3cf232434ef2"),
        "cars" : [ 
            {
                "parts" : [ 
                    {
                        "name" : "x1",
                        "price" : 12
                    }, 
                    {
                        "name" : "x2",
                        "price" : 14
                    }
                ]
            }, 
            {
                "parts" : [ 
                    {
                        "name" : "y1",
                        "price" : 8
                    }, 
                    {
                        "name" : "y2",
                        "price" : 12
                    }
                ]
            }
        ]
    }
    

    you can run the following query:

    db.collection.find({ "_id": ObjectId("555bd34329de3cf232434ef2"), "cars.parts.name" : "x1" }, { "_id": 0, "cars.$": 1 })
    

    which will get you pretty close to where you want to be:

    {
        "cars" : [ 
            {
                "parts" : [ 
                    {
                        "name" : "x1",
                        "price" : 12
                    }, 
                    {
                        "name" : "x2",
                        "price" : 14
                    }
                ]
            }
        ]
    }
    

    You could get closer using the aggregation framework if that's not good enough...