从mongo中的嵌入式文档多次查找相同的集合

时间:2018-09-14 06:20:49

标签: mongodb aggregation-framework pymongo

我有一个包含帖子和评论的嵌入式文档。注释是带有用户详细信息commentedby的嵌入式文档。用户名很有可能经常更改。因此,每次访问评论时都需要查找用户的值。

是否有使用mongo查询执行此操作的有效方法。 我不喜欢使用unwind ,因为我将在重新分组时失去其他发布参数

{
    "PostId":"Post001",
    "Comments":[
         {"_id": "001",
          "CommentedBy":{
            "_id":"User001",
            "Name":"UserName001",
            "email":"user001@eg.com"
            }
         },
         {"_id": "002",
           "CommentedBy":{
            "_id":"User002",
            "Name":"UserName002",
            "email":"user001@eg.com"
            }
         },
         {"_id": "003",
          "CommentedBy":{
            "_id":"User003",
            "Name":"UserName003",
            "email":"user001@eg.com"
            }
         }
    ]
}

用户文档不仅包含用户名和ID。使用多次查找可能最终会多次引用User001

预期结果

{
        "PostId":"Post001",
        "Comments":[
             {"_id": "001",
              "CommentedBy":{
                "_id":"User001",
                "Name":"UserName001",
                "email":"user001@eg.com",
                "Group":"Marketing",
                "Location":"India"                }
             },
             {"_id": "002",
               "CommentedBy":{
                "_id":"User002",
                "Name":"UserName002",
                "email":"user002@eg.com",
                "Group":"Engineering",
                "Location":"USA"         
                }
             },
             {"_id": "003",
              "CommentedBy":{
               "_id":"User002",
                "Name":"UserName002",
                "email":"user002@eg.com",
                "Group":"Engineering",
                "Location":"USA"      
                }
             }
        ]
    }

UserDocument看起来像这样

User = [
  {
  "_id":"User001",
  "Name":"UserName001",
  "email":"user001@eg.com",
  "Group":"Marketing",
  "Location":"USA"      
  },
  {
  "_id":"User002",
  "Name":"UserName002",
  "email":"user002@eg.com",
  "Group":"Engineering",
  "Location":"USA"      
  }
  ...
  ...
]

我尝试过的查询

db.getCollection('Posts').aggregate([
    {$lookup:{
           from: "User",
           localField: "Comments.CommentedBy._id",
           foreignField: "_id",
           as: "Comments.CommentedBy"
   }},
])
  1. 这对于带有n条评论的n条帖子有效吗
  2. mongo在查询User002时会进行某种优化,因为它需要被查询两次。
  3. 如果CommentedBy是用户在这种情况下如何执行$ lookup的列表

0 个答案:

没有答案
相关问题