我正在尝试填充声明对象内的 actions 数组中存在的 added_by 字段 这是一个例子:
{
_id: ObjectId('.....'),
actions: [
{
added_by: ObjectId('64d4f8a3fd3df..'),
message: 'test'
},
{
added_by: ObjectId('64d4f8a3fd3....'),
message: 'test2'
},
//rest of records
]
}
我想要实现的是:
{
_id: ObjectId('.....'),
actions: [
{
added_by: {
"email": "[email protected]",
// rest of properties
}
message: 'test'
},
{
added_by: added_by: {
"email": "[email protected]",
// rest of properties
},
message: 'test2'
},
//rest of records
]
}
我尝试这样做:
lookup.push({
$lookup: {
from: 'users', // The collection you are performing the lookup on (users collection)
let: { actions: '$actions' }, // Variable for matching IDs
as: 'actions', // The field to store the populated results
pipeline: [
{
$match: {
$expr: {
$in: ['$_id', '$$actions.added_by'], // Match users whose '_id' is in the 'added_by' array
},
},
},
],
},
});
但它有很多问题 1 - 它会覆盖整个对象,因此它将是这样的(消息字段将被删除 2-例如,如果 2 个操作是由同一用户在输出上创建的,我只找到 1 个用户,而不是输出同一用户两次
知道如何解决吗?
{
_id: ObjectId('.....'),
actions: [
{
added_by: {
"email": "[email protected]",
// rest of properties
}
},
{
added_by: added_by: {
"email": "[email protected]",
// rest of properties
},
},
//rest of records
]
}
这是一个完整的例子 索赔文件:
{
_id: ObjectId('64d79a9b5239b08bb7c00bb0'),
claim_message: 'hola',
files: [],
added_by: ObjectId('64d4f8a3fd3dfa4fd2a37607'),
company: ObjectId('64d4b30dfd3dfa4fd2a37283'),
services: [
ObjectId('64d4b0f4fd3dfa4fd2a3720f')
],
status: 'open',
createdAt: ISODate('2023-08-12T14:43:39.343Z'),
updatedAt: ISODate('2023-08-12T18:57:40.162Z'),
actions: [
{
files: null,
added_by: ObjectId('64d4f8a3fd3dfa4fd2a37607'),
message: 'testing'
},
{
files: null,
added_by: ObjectId('64d4f8a3fd3dfa4fd2a37607'),
message: 'new reply'
},
{
files: null,
added_by: ObjectId('64d4f8a3fd3dfa4fd2a37879'),
message: 'another reply'
},
]
}
用户收藏
{
{
_id: ObjectId('64d4f8a3fd3dfa4fd2a37607'),
account_type: 'CLIENT',
email: '[email protected]',
},
{
_id: ObjectId('64d4f8a3fd3dfa4fd2a37879'),
account_type: 'CLIENT',
email: '[email protected]',
}
}
一个选项是:
db.claims.aggregate([
{
$lookup: {
from: "users",
let: {
actions: "$actions"
},
as: "actionUsers",
pipeline: [
{
$match: {
$expr: {
$in: [
"$_id",
"$$actions.added_by"
]
}
}
}
]
}
},
{
$set: {
actions: {
$map: {
input: "$actions",
in: {
$mergeObjects: [
"$$this",
{
$arrayElemAt: [
"$actionUsers",
{
$indexOfArray: [
"$actionUsers",
{
$eq: [
"$$this.added_by",
"$_id"
]
}
]
}
]
}
]
}
}
},
actionUsers: "$$REMOVE"
}
}
])
查看它在 playground 示例中的工作原理