请看这个魔域playground ::mongoplayground
在这里,我使用$lookup在history array
中填充了user
个字段.但我得到了两个不同的回应.II如何将两个用户都推送到原始历史数组中?
用户在这里是一个字符串字段.
请帮帮忙.
请看这个魔域playground ::mongoplayground
在这里,我使用$lookup在history array
中填充了user
个字段.但我得到了两个不同的回应.II如何将两个用户都推送到原始历史数组中?
用户在这里是一个字符串字段.
请帮帮忙.
也可以做with unwinding和分组,但缺点是,你需要在小组赛阶段使用一堆$first
才不会丢失字段.因此,如果主文档中有很多字段,可能会出现一些重复
一种不放手的方法
history.user
转换为OBJECTIDusers
字段$map
通过历史记录数组,并 for each 用户搜索新添加的users
字段,并从$filter
中获取匹配的第一个元素users
字段db.approval.aggregate([
{ $match: {} },
{
$addFields: {
history: {
$map: {
input: "$history",
in: { $mergeObjects: [ "$$this", { user: { $toObjectId: "$$this.user" } } ] }
}
}
}
},
{
$lookup: {
from: "users",
localField: "history.user",
foreignField: "_id",
as: "users"
}
},
{
$addFields: {
history: {
$map: {
input: "$history",
in: {
$mergeObjects: [
"$$this",
{
user: {
$first: {
$filter: {
input: "$users",
as: "i",
cond: { $eq: [ "$$i._id", "$$this.user" ] }
}
}
}
}
]
}
}
}
}
},
{ $unset: "users" }
])
demo个