Node.js mongoDB聚合-同时匹配2个条件
我需要执行符合2个条件的操作:Node.js mongoDB聚合-同时匹配2个条件,node.js,mongodb,aggregation-framework,Node.js,Mongodb,Aggregation Framework,我需要执行符合2个条件的操作: id1->匹配ID数组 id2->匹配ID数组 我有与用户聊天的模式(Id的数组) 聚合查询: return await _chat.aggregate([{ $match: { // Here I nedd to match both cases $expr: { $in: [userId1, "$users"] }, $expr: { $in: [mongoose.Types.ObjectId(userI
- id1->匹配ID数组
- id2->匹配ID数组
return await _chat.aggregate([{
$match: { // Here I nedd to match both cases
$expr: { $in: [userId1, "$users"] },
$expr: { $in: [mongoose.Types.ObjectId(userId2), "$users"] }
}
},
{ $addFields: { totalMessages: { "$size": "$messages" } } },
{
$project: {
users: 1,
messages: { $slice: ["$messages", -20] },
totalMessages: 1,
createdAt: 1
}
},
{
$lookup: {
from: this._message.collection.name,
localField: 'messages',
foreignField: '_id',
as: 'messages',
}
}
])
我尝试使用$和
,但在$匹配
阶段不起作用
有人知道我怎么做吗?你可以简单地使用
工作得很好!。非常感谢。
return await _chat.aggregate([{
$match: { // Here I nedd to match both cases
$expr: { $in: [userId1, "$users"] },
$expr: { $in: [mongoose.Types.ObjectId(userId2), "$users"] }
}
},
{ $addFields: { totalMessages: { "$size": "$messages" } } },
{
$project: {
users: 1,
messages: { $slice: ["$messages", -20] },
totalMessages: 1,
createdAt: 1
}
},
{
$lookup: {
from: this._message.collection.name,
localField: 'messages',
foreignField: '_id',
as: 'messages',
}
}
])
{
$match: {
users: {
$all: [userId1, mongoose.Types.ObjectId(userId2)]
}
}
}