我有一个聚合查询,使用$lookup
从其他集合获取数据。但是我不明白如果找到一个$match
的布尔值怎么得到。
图式
const likesSchema = new mongoose.Schema({
user: {
id: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
},
storyID: {
type: String,
required: true,
}
}, {
timestamps: true
});
完整查询
const user_id = req.authorizedUser.sub;
const stories = await Story.aggregate([
{
$lookup: {
from: "comments",
localField: "storyID",
foreignField: "storyID",
as: "comments"
},
},
{
$lookup: {
from: "likes",
let: {storyID: "$storyID"},
pipeline: [
{
$match: {
$expr: { $eq: ["$$storyID", "$storyID"] }
}
},
{
$facet: {
"total": [{ $count: "count" }],
"byMe": [{
$match: {
$expr: { $eq: ["$user.id", user_id] } // Need boolean value if found/ not found
}
}]
}
}
],
as: "likes"
}
},
响应片段
"likes": [
{
"total": [
{
"count": 2
}
],
"byMe": [
{
"_id": "5d04fe8e982bb50bbcbd2b48",
"user": {
"id": "63p6PpPyOh",
"name": "Ayan Dey"
},
"storyID": "b0g5GA6ZJFKkJcnJlp6w8qGR",
"createdAt": "2019-06-15T14:19:58.531Z",
"updatedAt": "2019-06-15T14:19:58.531Z",
"__v": 0
}
]
}
]
所需的响应
"likes": {
"total": 2,
"byMe": true
}
最佳答案
您可以使用下面的聚合
{ "$lookup": {
"from": "likes",
"let": { "storyID": "$storyID" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$$storyID", "$storyID"] }}}
],
"as": "likes1"
}},
{ "$addFields": {
"likes.total": { "$size": "$likes1" },
"likes.byMe": { "$ne": [{ "$indexOfArray": ["$likes1.user.id", user_id] }, -1] }
}},
{ "$project": { "likes1": 0 }}
或
{ "$lookup": {
"from": "likes",
"let": { "storyID": "$storyID" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$$storyID", "$storyID"] }}},
{ "$facet": {
"total": [{ "$count": "count" }],
"byMe": [{ "$match": { "$expr": { "$eq": ["$user.id", user_id] }}}]
}}
{ "$project": {
"total": {
"$ifNull": [{ "$arrayElemAt": ["$total.count", 0] }, 0 ]
},
"byMe": { "$ne": [{ "$size": "$byMe" }, 0] }
}}
],
"as": "likes"
}},
{ "$unwind": "$likes" }
关于mongodb - 如何检查文档中是否存在元素并根据它返回true或false?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56619374/