简体   繁体   English

查看嵌套的对象数组是否包含值 | MongoDB

[英]See if nested array of objects contains value | MongoDB

I have a collection posts which has an array of objects comments .我有一个集合posts ,其中包含一组对象comments Within this array of objects, I have another array of objects likes .在这个对象数组中,我有另一个对象数组, likes .

I am trying to write a query that pulls the most recent 5 comments from a post, and only pulls true or false for likes , based on if the user has liked the comment already.我正在尝试编写一个查询,该查询从帖子中提取最新的 5 条评论,并且仅根据用户是否已经喜欢该评论来提取likes truefalse

I have written this so far:到目前为止,我已经写了这个:

db.posts.aggregate([
    {
        "$match": {
            "_id": postId
        }
    },
    {
        "$project": 
        {
            "comments": {
                "$slice": [ "$comments", -5 ]
            }
        }
    },
    {
        "$project": {
            "comments.content": 1,
            "comments.likes": { 
                "$eq":  [ "comments.likes.$.createdBy.username", username ] 
            } 
        }
    }
])

But this seems to pull false everytime.但这似乎每次都是false

Is it possible to do this without having to write a separate query to check if the user has liked?是否可以在不必编写单独的查询来检查用户是否喜欢的情况下执行此操作?

EDIT: So for the below document:编辑:所以对于下面的文件: 测试

With username = "testusername" , and postId = "60fcd335abbe5a73583b69f0"使用username = "testusername"postId = "60fcd335abbe5a73583b69f0"

I would expect output:我希望输出:

[
    {
        "content": "test comment",
        "likes": true
    },
    {
        "content": "another test comment",
        "likes": true
    }
]

And with username = "testusername2" I would expect output并使用username = "testusername2"我希望输出

[
    {
        "content": "test comment",
        "likes": true
    },
    {
        "content": "another test comment",
        "likes": false
    }
]

Answer回答

Thanks to @ray for your help with this one.感谢@ray 对这个问题的帮助。 Condensed Code Here though please see ray's response for the code split out with explanation.精简代码在这里,请参阅 ray 对代码的回应,并附有解释。

You can use $map to process your arrays layer-by-layer.您可以使用$map逐层处理您的数组。

  1. You can first $map comment to project a boolean for if the likes are liked by user1你可以先$map评论来投影一个布尔值,如果喜欢被用户 1
  2. Then you can use $anyElementTrue to perform the checking on the projected boolean然后您可以使用$anyElementTrue对投影布尔值执行检查

Here is the Mongo playground to show the idea(with some minor modification to your example).这是展示这个想法的Mongo 游乐场(对您的示例进行了一些小的修改)。 You can modify it to fit your needs.您可以修改它以满足您的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM