【问题标题】:MongoDB request on children array field, give back only matching childrenMongoDB对子数组字段的请求,只返回匹配的子项
【发布时间】:2019-04-18 15:00:43
【问题描述】:

我有一个集合,其中 docs 有子字段。 children 字段是一个数组,其中包含具有不同 _id 的对象。子 _id 在一个嵌套数组中是唯一的,但在 docs 数组之间可以找到相同的子 _id。

示例集合:

[{
    "_id" : 1,
    "name" : "Chocolate",
    "children" : [ 
        { "_id" : E, "bqt" : 23.26 }, 
        { "_id" : B, "bqt" : 0.093 },
        {..many children..}
    ]
},{
    "_id" : 2,
    "name" : "Cheese",
    "children" : [ 
        { "_id" : A, "bqt" : 4.55 }, 
        { "_id" : D, "bqt" : 0.044 },
        {..many children..}
    ]
},{
    "_id" : 3,
    "name" : "Pizza",
    "children" : [ 
        { "_id" : D, "bqt" : 9.35 }, 
        { "_id" : E, "bqt" : 2.31 },
        {..many children..}
    ]
}]

如何提出以下请求:

“哪些文档包含子 'E',匹配子的 'bqt' 值是多少?”仅将每个文档的匹配子文档归还给我,而不是全部文档

示例结果:

[{
    "_id" : 1,
    "name" : "Cheese",
    "children" : [ 
        { "_id" : E, "bqt" : 23.26 }
    ]
},{
    "_id" : 3,
    "name" : "Pizza",
    "children" : [ 
        { "_id" : E, "bqt" : 2.31 }
    ]
}]

更紧凑的示例结果:

[{
    "_id" : 1,
    "name" : "Cheese",
    "children.bqt" : 23.26
},{
    "_id" : 3,
    "name" : "Pizza",
    "children.bqt" : 2.31
}]

【问题讨论】:

    标签: arrays mongodb mongodb-query


    【解决方案1】:

    您可以使用$ positional operator for projection:

    db.col.find({ 'children._id': 'E' }, { 'children.$': 1 })
    

    将返回

    { "_id" : 1, "children" : [ { "_id" : "E", "bqt" : 23.26 } ] }
    { "_id" : 3, "children" : [ { "_id" : "E", "bqt" : 2.31 } ] }
    

    或$unwind 与$replaceRoot

    db.col.aggregate([
        {
            $unwind: "$children"
        },
        {
            $match: { "children._id": "E" }
        },
        {
            $replaceRoot: { newRoot: "$children" }
        }
    ])
    

    得到:

    { "_id" : "E", "bqt" : 23.26 }
    { "_id" : "E", "bqt" : 2.31 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-09
      • 2019-07-09
      • 2015-09-05
      • 2018-12-14
      • 2020-07-15
      • 2022-01-23
      • 1970-01-01
      • 2022-01-08
      相关资源
      最近更新 更多