【发布时间】:2021-10-01 12:37:16
【问题描述】:
我有一个集合posts,其中有一个对象数组comments。在这个对象数组中,我还有另一个对象数组likes。
我正在尝试编写一个查询,该查询从帖子中提取最近的 5 个 cmets,并且仅根据用户是否已经喜欢该评论来提取 true 或 false for likes。
到目前为止我已经写了这个:
db.posts.aggregate([
{
"$match": {
"_id": postId
}
},
{
"$project":
{
"comments": {
"$slice": [ "$comments", -5 ]
}
}
},
{
"$project": {
"comments.content": 1,
"comments.likes": {
"$eq": [ "comments.likes.$.createdBy.username", username ]
}
}
}
])
但这似乎每次都拉false。
是否可以这样做而无需编写单独的查询来检查用户是否喜欢?
username = "testusername" 和 postId = "60fcd335abbe5a73583b69f0"
我希望输出:
[
{
"content": "test comment",
"likes": true
},
{
"content": "another test comment",
"likes": true
}
]
而username = "testusername2" 我希望输出
[
{
"content": "test comment",
"likes": true
},
{
"content": "another test comment",
"likes": false
}
]
回答
感谢@ray 为您提供的帮助。 Condensed Code Here 虽然请参阅 ray 对代码拆分的响应,并附有解释。
【问题讨论】:
-
如果你能提供样本数据和预期输出给这里的每个人看看会很有帮助
-
另一条建议:将代码/示例数据粘贴为文本而不是图像;其他人会更容易复制和复制它
标签: mongodb mongoose mongodb-query aggregation-framework