我有两个收藏
有模式的
{
a : Array,
b : ObjectID
}
和 B 具有以下架构
{
x : 'string',
y : // some object schema
...
b : ObjectID
}
我想使用 mongo 聚合在集合 B 中添加一个新字段,以仅包含使用 b 搜索的集合 A 中的一个。
我希望聚合后的值具有以下架构:
{
x : 'string',
newField : a // array from collection A
y : // some object schema
...
b : ObjectID
}
只有 $lookup 不起作用,因为我不想要整个对象,而且合并将删除 _id 并合并我不想要的其他对象。
最佳答案
我在解决后自己回答这个问题。
这可以作为操作管道完成,如下所示:
{
$lookup: {
from: "A",
localField: "b",
foreignField: "b",
as: "someField"
}
},
{
$addFields: {
newField : "$someField.a"
}
},
{
$unwind: "$newField"
},
{
$project: {
someField: 0
}
}
将接受更高效的答案
关于mongodb - 在 MongoDB 中仅添加另一个集合中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51010754/