【问题标题】:Pymongo join using lookupPymongo 使用查找加入
【发布时间】:2021-07-30 16:45:14
【问题描述】:

我有两个收藏:

post = {
   "_id" : 102,
   "categories": [
      {'id': ObjectId('6054603f3e1967165a3e70f2'),'name': 'Acting'},
      {'id': ObjectId('605460403e1967165a3e70f6'), 'name': 'Singing'}]
     }
content = {
   "_id" : ObjectId('6054603f3e1967165a3e70f2'),
   "name" : 'Acting'
}

所以我想加入:

out = [{
   "_id" : 102,
   "name" : ["Acting", "Singing"]}]

但在确保代理的 id 在两个集合中相同之后。 因此,为此我正在尝试在两个集合之间加入。 这是我尝试过的:

temp = list(posts.aggregate([
    ...:   {"$unwind" : "$categories"},
    ...:   {"$lookup" : {
    ...:                "from" : "content_categories",
    ...:                "localField" : "categories.id",
    ...:                "foreignField" : "_id",
    ...:                "as" : "temp"
    ...:               }
    ...:   },
    ...:   {"$unwind" : "$temp"},
    ...:   {"$group" : {
    ...:                "_id": "$_id", "name":{"$first":"$temp.name"}
    ...:               }
    ...:   }]))

但我只得到一个名称值(我猜是 id 的第一次出现),而不是名称列表。 我已经交叉检查了所有值都存在于 temp 变量中。那么我应该如何获取这些值作为 name = ["Acting", "Singing"]

【问题讨论】:

  • 您想获取类别数组中的所有值,但请检查两个集合中是否存在代理 ID,对吗?但是如果条件匹配或不匹配,预计会有什么行为?
  • 是的,这就是我想要的......我只想要两个集合中 id 匹配的值,如果不匹配则忽略。

标签: mongodb collections mongodb-query aggregation-framework pymongo


【解决方案1】:

这对我有用:

temp = list(posts.aggregate([
          {"$unwind" : "$categories"},
          {"$lookup" : {
                       "from" : "content_categories",
                       "localField" : "categories.id",
                       "foreignField" : "_id",
                       "as" : "temp"
                     }
          },
          {"$unwind" : "$temp"},
          {"$project" : {
                       "_id": 1, "temp.name" : 1
                      }
          }
        ]))

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多