node.js - 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;
})
想法???
解决方案
在展开成员数组之前,项目成员数组作为两个新字段,然后展开两个新字段中的任何一个。例如
{
"_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 字段。
推荐阅读
- asp.net-core - 仅在 IIS 中使用 asp.net 核心未发现局部视图异常
- docker - 如何在我的 docker 映像 apache/airflow:2.1.4 上安装 gecko 驱动程序和 firefox
- c# - 无法从程序集“Volo.Abp.Authorization.Abstractions,Version=4.4.2.0”加载类型“Volo.Abp.Authorization.Permissions.IPermissionStateManager”,
- react-native - watchPosition 的问题反应原生博览会
- java - 如何修复不支持的 major.minor 版本 52.0 异常?
- keras - 如何解决 ValueError: Graph disconnected: cannot get value for tensor Tensor("input_1:0", shape=(?, 784), dtype=float32) at layer "input_1"
- javascript - 如何使用 Javascript 将值从一个 HTML 页面传递到另一个 HTML 页面
- npm - 在 chrome 中失败 - /splitscenarios/Wireless_Internet_Inventory_page_test.16336592073782.feature
- javascript - `yarn run build` 在我的 docker build 中运行时出现 Webpack 错误
- javascript - 对 Velo 的 Python 异步 HTTP 请求不等待来自 javascript 的承诺