在MongoDB中的2个级别的嵌套数组中查找

Mar*_* Jr 3 mongodb mongodb-query

经过大量搜索之后,我找不到能够解决此问题的东西。我想这应该很简单。我有这个简单的json ...

{
"_id" : ObjectId("555bd34329de3cf232434ef2"),
"clients" : [ 
    {
        "Client1" : {
            "positions" : [ 
                {
                    "systemId" : "xxx1",
                    "type" : "alfa"
                },
                {
                    "systemId" : "xxx2",
                    "type" : "bravo"
                },
                {
                    "systemId" : "xxx3",
                    "type" : "charlie"
                }
            ]
        },
        "Client2" : {
            "positions" : [ 
                {
                    "systemId" : "xxx4",
                    "type" : "alfa"
                },
                {
                    "systemId" : "xxx5",
                    "type" : "bravo"
                },
                {
                    "systemId" : "xxx6",
                    "type" : "charlie"
                }
            ]
        } 
    }
]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试基于{systemId}进行查询,该查询是在另一个数组内部的数组中的positions数组中。我可以轻松地在单个级别的数组中使用find()。但是这时我需要更多的深度,我真的面临困难。有人可以帮我吗?

tyvm!

Yog*_*esh 5

如果你想找出Client1.positionssystemIdClient2.positionssystemId使用以下聚合:

db.collectionName.aggregate([
    {
        "$unwind": "$clients"
    },
    {
        "$unwind": "$clients.Client1.positions"
    },
    {
        "$unwind": "$clients.Client2.positions"
    },
    {
        "$match": {
            "clients.Client1.positions.systemId": "xxx1",
            "clients.Client2.positions.systemId": "xxx4"
        }
    }
]).pretty()
Run Code Online (Sandbox Code Playgroud)

如果您只想查找,Client1则删除"$unwind": "$clients.Client2.positions"并匹配"clients.Client2.positions.systemId": "xxx4"