选择要从$lookup返回的字段

2024-05-08 19:12:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码将集合a(示例)连接到集合B(定位器)。我试过$unwind$group$push语法唯一的问题是我不能返回字段locator和{}。在


data = db.sample.aggregate([
{'$lookup': {
    'from': 'locators',
    'localField': "locator",
    'foreignField': "_id",
    'as': "metalocator"}}])

print(list(data))

它回来了

^{pr2}$

尝试1

data = db.sample.aggregate([
    {"$lookup": {"from": "locators",
                 "localField": "locator",
                 "foreignField": "_id",
                 "as": "metalocator"}},
    {"$unwind": '$metalocator'},
    {"$group": {"_id": "$_id",
                "metalocator": {"$push":  {
                    "section": "$metalocator.section",
                    "cabinet": "$metalocator.cabinet"}}}}
])
print(list(data))

返回:

[
  {
    '_id': '1835853D2982AAEF',
    'metalocator': [{'section': 'Geo', 'cabinet': 'Country'}]
  },
  {
    '_id': '428E970995AE8C76',
    'metalocator': [{'section': 'Geo', 'cabinet': 'Country'}]
  }
]

预期结果应为:

[
  {
    '_id': '1835853D2982AAEF',
    'locator': 'ABC',
    'record': 'Nicaragua',
    'metalocator': [{'section': 'Geo', 'cabinet': 'Country'}]
  },
  {
    '_id': '428E970995AE8C76',
    'locator': 'CDE',
    'record': 'Nigeria',
    'metalocator': [{'section': 'Geo', 'cabinet': 'Country'}]
  }
]

Tags: sampleiddbdatagroupsectionlookupcountry
1条回答
网友
1楼 · 发布于 2024-05-08 19:12:00

您想要^{}

db.sample.aggregate([
  {'$lookup': {
    'from': 'locators',
    'localField': "locator",
    'foreignField': "_id",
    'as': "metalocator"
  }},
  { '$addFields': {
    'metalocator': {
      '$map': {
        'input': '$metalocator',
        'in': {
          'section': '$$this.section',
          'cabinet': '$$this.cabinet'
        }
      }
    }
  }}
 ])

这就是您用来“重新映射”数组内容的方法,这正是您所要求的。它的用法与python以及许多其他语言中的操作符的用法非常相似。在

如果您有MongoDB 3.6,您也可以使用不同的^{}语法,在这里您可以实际“选择”要从那里返回的字段:

^{pr2}$

如果可以这样做的话,这实际上会更有效,因为数据甚至不会返回到目标数组中,而且您不需要为了丢弃其他字段而“重新映射”数组。在

根据记录,您“遗漏”的是^{}运算符:

db.sample.aggregate([
  { "$lookup": {
    "from": "locators",
    "localField": "locator",
    "foreignField": "_id",
    "as": "metalocator"
  }},
  { "$unwind": '$metalocator'},
  { "$group": {
    "_id": "$_id",
    "locator": { "$first": "$locator" },
    "record": { "$first": "$record" },
    "metalocator": {
      "$push":  {
        "section": "$metalocator.section",
        "cabinet": "$metalocator.cabinet"
      }
    }
  }}
])

但是这里不需要使用^{}和{a5},因为上面显示的其他方法要高效得多。在

相关问题 更多 >