Projections in Mongodb Nested Arrays

I have a heavily nested document in Mongodb that follows this order:

site → rooms → ups → batteryStrings → batteries.

I am trying to return only the appropriate batteries and their batteries in the box batteryString _id.

db.getCollection('sites').find({
    "rooms.ups.batteryStrings._id": ObjectId("55dc967efefd4e6a14332019")
    }, {
        "rooms.ups.batteryStrings.batteries.$": 1,
        "siteName": 1
    }
)

I get the following which has 2 batteries. I would like to return the 2nd battery rod (highlighted in yellow) along with its batteries.

enter image description here

I initially tried to do this, but got the same results:

db.getCollection('sites').find({
"rooms.ups.batteryStrings._id": ObjectId("55dc967efefd4e6a14332019")
}, {
    "rooms.ups.batteryStrings.$": 1,
    "siteName": 1
})
+4
source share
1 answer

. $match, , . , $unwind , . $match, . , $project, , , . . , :

db.sites.aggregate([
    {
        "$match": {
            "rooms.ups.batteryStrings._id": ObjectId("55dc967efefd4e6a14332019")
        }
    },
    { "$unwind": "$rooms" },
    { "$unwind": "$rooms.ups" },
    { "$unwind": "$rooms.ups.batteryStrings" },
    {
        "$match": {
            "rooms.ups.batteryStrings._id": ObjectId("55dc967efefd4e6a14332019")
        }
    },
    {
        "$project": {
            "siteName": 1,
            "batteryStrings": "$rooms.ups.batteryStrings"
        }
    }
])

:

/* 0 */
{
    "result" : [ 
        {
            "_id" : ObjectId("5613c98a645a64b1a70af2c1"),
            "siteName" : "OGG",
            "batteryStrings" : {
                "name" : "String 1",
                "ctrlId" : "bmstest11",
                "_id" : ObjectId("55dc967efefd4e6a14332019"),
                "batteries" : [ 
                    {
                        "name" : "String 2a",
                        "ctrlId" : "bmstest11",
                        "_id" : ObjectId("55e67b28010000880ca4c045")
                    }, 
                    {
                        "name" : "String 2b",
                        "ctrlId" : "bmstest11",
                        "_id" : ObjectId("55ea1b520100006d004e602a")
                    }, 
                    {
                        "name" : "String 2c",
                        "ctrlId" : "bmstest11",
                        "_id" : ObjectId("55ea1b520100006d004e602b")
                    }
                ]
            }
        }
    ],
    "ok" : 1
}
+2

All Articles