我有一段代码将集合a(示例)连接到集合B(定位器)。我试过$unwind
、$group
和$push
语法唯一的问题是我不能返回字段locator
和{
data = db.sample.aggregate([
{'$lookup': {
'from': 'locators',
'localField': "locator",
'foreignField': "_id",
'as': "metalocator"}}])
print(list(data))
它回来了
^{pr2}$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'}]
}
]
您想要^{} :
这就是您用来“重新映射”数组内容的方法,这正是您所要求的。它的用法与python以及许多其他语言中的操作符的用法非常相似。在
如果您有MongoDB 3.6,您也可以使用不同的^{} 语法,在这里您可以实际“选择”要从那里返回的字段:
^{pr2}$如果可以这样做的话,这实际上会更有效,因为数据甚至不会返回到目标数组中,而且您不需要为了丢弃其他字段而“重新映射”数组。在
根据记录,您“遗漏”的是^{} 运算符:
但是这里不需要使用^{} 和{a5},因为上面显示的其他方法要高效得多。在
相关问题 更多 >
编程相关推荐