Node.js MongoDB$展开并保留每个展开文档的数组字段,以供参考

Node.js MongoDB$展开并保留每个展开文档的数组字段,以供参考,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我希望将原始数组字段保留在每个未缠绕的文档中 示例:在展开band的成员数组时,我希望在每个文档中保留原始成员数组,以便我可以引用其他成员 { 'name': 'the crazies', 'member': 'Tom', 'othermembers': [ 'Tom', 'Mike', 'Sally' ] } { 'name': 'the crazies', 'member': 'Mike', 'othermembers': [ 'Tom', 'Mike', 'Sally' ] } { '

我希望将原始数组字段保留在每个未缠绕的文档中

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

{ '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' ] }
最终,members数组不应该在'name'字段中包含已经存在的成员的名称,但如果有人有任何想法,我将接受我能得到的

一种有效的方法是通过band 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;
})

想法???

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

{
"_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
    ]
}

因此,旧的\u arr字段是展开的,但是对于每个文档,您将有一个包含所有值的新\u arr字段。

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

{
"_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
    ]
}
因此,旧的\u arr字段是不需要的,但是对于每个文档,您将有一个包含所有值的新\u arr字段