在 MongoDB 中查找 2 层嵌套数组

Find in 2 levels of nested arrays in MongoDB

谷歌搜索了很多之后,我找不到可以处理这个问题的东西。我想这应该很简单。我有这个简单的 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"
                }
            ]
        } 
    }
]
}

我正在尝试基于 {systemId} 执行查询,查询位置数组位于另一个数组内的数组内。我可以轻松地在单级数组中使用 find()。但此时我需要一个额外的深度,我真的面临困难。有人可以帮我吗?

tyvm !

根据您的示例数据,clients 包含不同的对象,如 Client1 Client2 等,进一步包含 positions 对象数组。在这种情况下要找到 systemId,您需要使用 $elemMatch,如下所示:

db.collection.find({
  "clients": {
    $elemMatch: {
        "Client2.positions": {
            $elemMatch: {
                "systemId": "xxx4"
            }
        }
    }
  }
})

如果您想用 systemId 找出 Client1.positions 并用 systemId 找出 Client2.positions,请使用以下聚合:

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()

如果你只想找出 Client1 然后删除 "$unwind": "$clients.Client2.positions" 并匹配 "clients.Client2.positions.systemId": "xxx4"