mongodb - 在 MongoDB 中查找 2 级嵌套数组

标签 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"
                }
            ]
        } 
    }
]
}

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

你好!

最佳答案

如果你想找出 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()

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

关于mongodb - 在 MongoDB 中查找 2 级嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30354323/

相关文章:

mongodb - Meteor mongo find()UnhandledPromiseRejectionWarning,超过最大调用堆栈大小

javascript - 比较三个日期以获得最新的 MongoDB

mongodb - Mongo UUID 类型 03 而不是来自 mongo shell 的 04

mongodb - 从 $lookup 中获取数组中元素的过滤计数以及整个文档

java - 如何使用 Hibernate OGM 和 MongoDB 删除数据库或集合

使用嵌入文档作为键的 MongoDB 查询

MongoDB如何通过搜索混合模式字段来查找文档?

通过 zip 进行 MongoDB 地理空间搜索

mongodb - Mgo 聚合管道 $not 运算符。未知的顶级运算符(operator)

node.js - MongoDB:如果字段值小于10,则将字段值设置为10,否则加1