我有 2 个集合假设为 1 对多关系,例如用户和评论。要求是将用户与其最新评论合并为单个对象,并返回新合并对象的列表作为结果。
聚合在 mongo 控制台中完美运行
db.user.aggregate(
{
$addFields:{
cId: {$toString: '$_id'},
user: '$$ROOT'
}
},
{$match: {'invitees': {$elemMatch: {'user.userId': '5e70e82532044a5e4e7cbc8d'}}}},
{$lookup: {
from: 'comment',
let: {'cc': '$cId'},
pipeline: [
{$match: {$expr: {$and: [{$eq: ['$$cc', '$userId']},{$gte: ['$time', '$$NOW']}]}}},
{$sort: {'time': -1}},
{$limit: 1}
],
as: 'next'
}
},
{$unwind: {path: '$next'}},
{
$project: {
_id: 0,
user: 1,
next: 1,
status: {
$map: {
input: {
$filter: {
input: '$invitees',
as: 'item',
cond: {
$eq: ['$$item.user.userId', '$userId']
} …Run Code Online (Sandbox Code Playgroud)