我想在聚合階段后根據一個條件來獲取結果。我的代碼給了我一個包含4個結果的陣列,而不是3個。 該邏輯是用戶刷卡,資料存盤在一個集合中。集合存盤了第一次刷卡,如果其他用戶刷了一個現有的條目,集合檔案就會被更新,而不是根據誰先刷卡進行新的插入,因此有$or查詢。這樣做很好,直到我在用戶集合中把一個現有用戶的鉤子狀態改為假。這個額外的陣列是由$or查詢創建的,并且只有user_two。
重繪 集合 _id(ObjectID) - user_one(string) - user_two(string) - status_one(number) - status_two(number) /p>
用戶集合 _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"/span>, '$user_one'/span>] },
{ $eq: ["$hookups", '$hookupstatus'] 。},
],
}
}
}],
as: "userone"。
}
},
{
$unwind: {
path: "$userone"/span>,
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'users',
let: { user_two: '$user_two', hookupstatus: true }。
pipeline: [{
$match: {
$expr: {
$and: [
{ $eq: ["$_id"/span>, '$user_two'/span>] },
{ $eq: ["$hookups", '$hookupstatus'] 。},
],
}
}
}],
as: "usertwo"。
}
},
{
$unwind: {
path: "$usertwo"/span>,
preserveNullAndEmptyArrays: true,
},
},
{
$sort: {
_id: -1
}
}
]).exec(function(error, response) {
if (error) {
console.log(error)
} else {
res.json(回應)。
}
})
uj5u.com熱心網友回復:
{
$redact: {
$cond: [{
$eq: ["$userone.hookups", true],
$eq: ["$usertwo.hookups", true],
},
"$KEEP",
"$PRUNE", "$KEEP".
]
}
},
uj5u.com熱心網友回復:
我沒有試過,但是$redact運算子聽起來像是在做你想要的事情。
這里有一個相當古老但寫得很好的例子。 查找陣列欄位至少包含一個給定陣列的n個元素的檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/319148.html
標籤:
