arrays - 在单个聚合中多次查找后合并 Mongo 文档
问题描述
我一直在尝试合并我的文档结果。这是我的查询和数据
{"_id":"5c21ab13d03013b384f0de26",
"roles":["5c21ab31d497a61195ce224c","5c21ab4ad497a6f348ce224d","5c21ab5cd497a644b6ce224e"],
"agency":"5b4ab7afd6ca361cb38d6a60","agents":["5b4ab5e897b24f1c4c8e3de3"]}
这是查询
return db.collection('projects').aggregate([
{
$match: {
agents: ObjectId(agent)
}
},
{
$unwind: "$agents"
},
{
$lookup: {
from: "agents",
localField: "agents",
foreignField: "_id",
as: "agents"
}
},
{
$unwind: {
path: "$roles",
preserveNullAndEmptyArrays: true
}
},
{
$lookup: {
from: "roles",
localField: "roles",
foreignField: "_id",
as: "roles"
}
},
{
$lookup: {
from: "agencies",
localField: "agency",
foreignField: "_id",
as: "agency"
}
}
])
如您所见,项目集合中的条目有两个数组,在对每个条目执行查找之前展开,然后在“代理”字段上执行最终查找。
但是,当我从这个查询中得到结果时,我得到的文档计数等于角色的数量。例如,我正在聚合的项目有 3 个角色和 1 个代理。所以我得到了一个包含 3 个对象的数组,每个角色一个,而不是一个文档,其中角色数组包含所有三个角色。代理数组也有可能具有多个值。
好失落...
解决方案
您不必在$lookup$unwind
之前运行。该部分指出:localField
如果您的 localField 是一个数组,您可能需要在管道中添加一个 $unwind 阶段。否则localField和foreignField相等的条件是foreignField: { $in: [ localField.elem1, localField.elem2, ... ] }
所以基本上,如果你不运行$unwind
thenroles
而不是每个角色的文档,你将得到一个roles
as的数组,ObjectIds
替换为第二个集合中的对象数组。
因此,您可以尝试以下聚合:
db.collection('projects').aggregate([
{
$match: {
agents: ObjectId(agent)
}
},
{
$lookup: {
from: "agents",
localField: "agents",
foreignField: "_id",
as: "agents"
}
},
{
$lookup: {
from: "roles",
localField: "roles",
foreignField: "_id",
as: "roles"
}
},
{
$lookup: {
from: "agencies",
localField: "agency",
foreignField: "_id",
as: "agency"
}
}
])
推荐阅读
- javascript - 无法读取未定义的属性“配置”
- c# - 使用jquery获取日期时如何更改日期格式
- c# - 在调用 BuildServiceProvider 之前将 dotnet 核心依赖注入到扩展方法
- html - 所有断点移动设备、平板电脑和网站上的图像大小 fiz
- javascript - 使用 JS 插入后 HTML 实体无法正确显示
- javascript - 从 Formik 的 Field 的输入中获取值
- kotlin - 有没有办法将扩展属性添加到列表中
在科特林? - bluetooth-lowenergy - Android BLE DFU多台设备陆续更新...但部分设备更新失败
- selenium - 如何处理硒中的a标签
- mysql - MYSQL 别名:无法为新表命名