如何解决mongoDB聚合-同时匹配2个条件
我需要执行一个符合2个条件的操作:
- id1->匹配IDs数组
- id2->匹配ID数组。
我有一个与用户聊天的模型(一组ID)。
const ChatSchema = new Schema(
{
users: {
type: [{
type: Schema.Types.ObjectId,ref: 'User'
}]
},messages: {
type: [{
type: Schema.Types.ObjectId,ref: 'Message'
}]
},},{
toObject: { virtuals: true },toJSON: { virtuals: true },timestamps: true
}
);
汇总查询:
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',}
}
])
我尝试使用$and
,但在$match
阶段无法正常工作。
有人知道我该怎么做吗?
解决方法
您只需使用$all,
{
$match: {
users: {
$all: [userId1,mongoose.Types.ObjectId(userId2)]
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。