首页 > 解决方案 > 如何在mongodb中查询文档的多层

问题描述

我在 mongodb 中有一个看起来像这样的模型......

{
    username: 'bob', 
    user_id: '12345',
    post: 'Hey everyone, this is my post',
    photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
    comments: [
        {
            username: 'tom', 
            user_id: '54321',
            post: 'Hey everyone, this is comment 1',
            photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
            responses: [
                {
                    username: 'bob', 
                    user_id: '12345',
                    post: 'Hey everyone, this is response 2',
                    photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
                },
                {
                    username: 'will', 
                    user_id: '35791',
                    post: 'Hey everyone, this is response 2',
                    photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
                }
            ]
        },
        {
            username: 'bob', 
            user_id: '12345',
            post: 'Hey everyone, this is comment 2',
            photoID: RANDOM_GENERATED_NUMBER, // each user has their own photoID
            responses: []
        }
    ]
}

在我的网站上,每次用户更改他们的个人资料图片时,他们都会获得一个新的“photoID”,引用图片,因此可以轻松地将其用户名显示在他们发布的任何帖子上方。因此,当用户更新他们的个人资料图片并获得新的“photoID”时,我需要能够对这个“帖子”模型进行查询,以搜索任何“帖子”、“评论”或“回复”由“鲍勃”发布。然后,我需要更新该“帖子”、“评论”或“回复”的 photoID。

有没有我可以用来执行此操作的查询?

标签: mongodb

解决方案


您可以使用嵌套elemMatch查询。

如何使用 elemMatch 匹配嵌套数组的可能重复项


推荐阅读