Jorge Rosa
Jorge Rosa

Reputation: 63

MongoDB query with embedded document in array (3 levels)

I had this data on my MongoDB database and I would like to get only the second array about blades.

{
"_id" : ObjectId("..."),
"name" : "Westereems",
"country" : "Netherlands",
"turbines" : [
    {
        "turbine_id" : ObjectId("..."),
        "blades" : [
            {
                "blade_id" : ObjectId("..."),
                "position" : 2,
                "size" : 50,
            }
        ]
    }
]
}

I only want one return with blade_id, position and size. I tried this query and I didn't have the expectable result:

db.collection("windfarms").find({"turbines.blades.blade_id" : ObjectId("...")}, {"turbines.blades.$" : 1, "_id" : 0})

Regards,

Upvotes: 0

Views: 307

Answers (1)

abdulbari
abdulbari

Reputation: 6232

You can use this query, it's not an optimal query for large array's items but if you have only above items then you can use it.

you can also go with aggregation to make it more optimal.

db.collection("windfarms").find({"turbines.blades.blade_id" : ObjectId("...")}, {"turbines.blades.blade_id":1,"turbines.blades.position":1,"turbines.blades.size":1,"_id":0})

Upvotes: 1

Related Questions