如何查找与Array中的Object属性匹配的数据

时间:2017-05-30 07:10:31

标签: mongodb mongodb-query aggregation-framework

假设我有数据库结构;

[

    {id:1, name: "alex", children: [ {id: 2}, {id: 5}]},
    {id:2, name: "felix", children: []},
    {id:5, name: "tom", children: [{id: 6}]},
    {id:6, name: "hannah", children: []}
]

我想将名字字段添加到id匹配的子数组中。我想说的是,我想写一个返回为的查询;

[

    {id:1, name: "alex", children: [ {id: 2, name: "felix"}, {id: 5, name: "tom"}]},
    {id:2, name: "felix", children: []},
    {id:5, name: "tom", children: [{id: 6, name: hannah}]},
    {id:6, name: "hannah", children: []}
]

能够做到这一点。首先,我考虑将匹配记录作为;

db.collection.aggregate([
    {$lookup: {from: "collection", localField: "children.id", foreignField: "id" , as: "array"}},
])

但是array返回为空。我无法走得更远。 我该如何修改查询?我应该从哪里开始?

0 个答案:

没有答案