经过Google搜索后,我无法找到可以处理此问题的内容。我猜,它应该很简单。我是这个简单的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!
答案 0 :(得分:3)
如果您希望找到Client1.positions
systemId
和Client2.positions
systemId
,请使用以下聚合:
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"
答案 1 :(得分:1)
根据您的示例数据,clients
包含不同的对象,例如Client1
Client2
等,其中还包含positions
个对象数组。在这种情况下,要查找systemId
,您需要使用$elemMatch,如下所示:
db.collection.find({
"clients": {
$elemMatch: {
"Client2.positions": {
$elemMatch: {
"systemId": "xxx4"
}
}
}
}
})