如何限制MongoDB在聚合阶段之后的结果与条件



我想在聚合阶段之后根据条件获取结果。我的代码给了我一个数组的4个结果,而不是3。逻辑是将用户的滑动和数据存储在一个集合中。集合存储第一次滑动,如果其他用户滑动现有条目,则集合文档更新而不是新插入,这取决于谁先滑动,因此是$或查询。在我将用户集合上的现有用户的连接状态更改为false之前,这一切都很正常。结果生成长度为4而不是3的数组。额外的数组是从$or查询创建的,并且只有user_two。

刷收藏_id(ObjectID) - user_one(string) - user_two(string) - status_one(number) - status_two(number)

用户集合_id(ObjectID) - user_name(string) - hookups(boolean)

const fetchHookups = (req, res, next) => {
var query = {
$or: [
{ user_one: ObjectId(req.body._id)},
{ user_two: ObjectId(req.body._id) },
]
}

Swipe.aggregate([{
$match: query
},
{
$lookup: {
from: 'users',
let: { user_one: '$user_one', hookupstatus: true },
pipeline: [{
$match: {
$expr: {
$and: [
{ $eq: ["$_id", '$$user_one'] },
{ $eq: ["$hookups", '$$hookupstatus'] },
],
}
}
}],
as: "userone"
}
},
{
$unwind: {
path: "$userone",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'users',
let: { user_two: '$user_two', hookupstatus: true },
pipeline: [{
$match: {
$expr: {
$and: [
{ $eq: ["$_id", '$$user_two'] },
{ $eq: ["$hookups", '$$hookupstatus'] },
],
}
}
}],
as: "usertwo"
}
},
{
$unwind: {
path: "$usertwo",
preserveNullAndEmptyArrays: true,
},
},
{
$sort: {
_id: -1
}
}
]).exec(function(error, response) {
if (error) {
console.log(error)
} else {
res.json(response)
}
})
}

多亏了@Thomas,我找到了答案:

{
$redact: {
$cond: [{
$eq: ["$userone.hookups", true],
$eq: ["$usertwo.hookups", true],
},
"$$KEEP",
"$$PRUNE"
]
}
},

我没有试过,但是$redact操作符听起来像是您想要的。

这是一个相当古老但写得很好的例子:查找数组字段至少包含n个给定数组元素的文档

最新更新