MongoDB在子级数组字段上的请求,只返回匹配的子级

时间:2019-04-18 15:00:44

标签: arrays mongodb mongodb-query

我有一个集合,其中docs具有children字段。 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
}]

1 个答案:

答案 0 :(得分: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 }