首页 > 解决方案 > MongoDB $unwind 并保留每个展开文档的数组字段以供参考

问题描述

我想将原始数组字段与每个展开的文档一起保留。

示例:展开乐队的成员数组时,我想将原始成员数组保留在每个文档中,以便可以引用其他成员

{ 'name': 'the crazies', 'member': 'Tom', 'othermembers': [ 'Tom', 'Mike', 'Sally' ] }

{ 'name': 'the crazies', 'member': 'Mike', 'othermembers': [ 'Tom', 'Mike', 'Sally' ] }

{ 'name': 'the crazies', 'member': 'Sally', 'othermembers': [ 'Tom', 'Mike', 'Sally' ] }

最终,成员数组不应包含已在“名称”字段中的成员名称,但如果有人有任何想法,我会尽我所能。

一种可行的方法是通过乐队 ID 对自身进行 $lookup,但看起来有点笨拙。

band.aggregate()
  .match( 'whatever criteria' )
  .lookup({ from: 'bands', localField: '_id', foreignField: '_id', as       'othermembers')
  .unwind({ path: 'members')
  .project({
    'name': 1
    'member': '$members.name',
    'othermembers.members.name': 1;
})

想法???

标签: node.jsmongodbmongoose

解决方案


在展开成员数组之前,项目成员数组作为两个新字段,然后展开两个新字段中的任何一个。例如

{
"_id" : ObjectId("5c5ca7184ef14365b786e11f"),
"a" : [ 
    10, 
    20, 
    30
],
"b" : "hello"

}

对于上述数据,我正在使用以下查询

db.testColl.aggregate([
{$project: {old_arr: "$a", new_arr: "$a"}},
{$unwind: {path: "$old_arr"}}
])

我得到的结果是

    {
    "_id" : ObjectId("5c5ca7184ef14365b786e11f"),
    "old_arr" : 10,
    "new_arr" : [ 
        10, 
        20, 
        30
    ]
}

{
    "_id" : ObjectId("5c5ca7184ef14365b786e11f"),
    "old_arr" : 20,
    "new_arr" : [ 
        10, 
        20, 
        30
    ]
}

{
    "_id" : ObjectId("5c5ca7184ef14365b786e11f"),
    "old_arr" : 30,
    "new_arr" : [ 
        10, 
        20, 
        30
    ]
}

因此 old_arr 字段是展开的,但是对于每个文档,您将拥有包含所有值的 new_arr 字段。


推荐阅读