[英]See if nested array of objects contains value | MongoDB
我有一个集合posts
,其中包含一组对象comments
。 在这个对象数组中,我有另一个对象数组, likes
.
我正在尝试编写一个查询,该查询从帖子中提取最新的 5 条评论,并且仅根据用户是否已经喜欢该评论来提取likes
true
或false
。
到目前为止,我已经写了这个:
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 对这个问题的帮助。 精简代码在这里,请参阅 ray 对代码的回应,并附有解释。
您可以使用$map
逐层处理您的数组。
$map
评论来投影一个布尔值,如果喜欢被用户 1$anyElementTrue
对投影布尔值执行检查这是展示这个想法的Mongo 游乐场(对您的示例进行了一些小的修改)。 您可以修改它以满足您的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.