Python 带投影运算符的Pymongo查找
我有一个嵌套的mongodb数据库,我正在尝试执行一个查询,该查询查找条目并仅返回某些字段 我要返回的字段是嵌套的 数据库如下所示Python 带投影运算符的Pymongo查找,python,mongodb,operators,pymongo,projection,Python,Mongodb,Operators,Pymongo,Projection,我有一个嵌套的mongodb数据库,我正在尝试执行一个查询,该查询查找条目并仅返回某些字段 我要返回的字段是嵌套的 数据库如下所示 { 'material_type':'solid', 'performance':10, 'material': {'isotopes': [ { 'abundance': 0.9, 'atomic_number': 6, },
{
'material_type':'solid',
'performance':10,
'material': {'isotopes': [ { 'abundance': 0.9,
'atomic_number': 6,
},
{ 'abundance': 0.1,
'atomic_number': 7,
}
]
},
},
{
'material_type':'solid',
'performance':9,
'material': {'isotopes': [ { 'abundance': 0.7,
'atomic_number': 6,
},
{ 'abundance': 0.3,
'atomic_number': 7,
}
]
}
}
我想返回嵌套的丰度字段,但仅当原子序数等于6时才返回
我尝试过对查询执行投影,目前在python pymongo中有类似的东西
results = database.find({'material_type':'solid'},
{'performance':True,
'material.isotopes':True
})
我想我需要一个投影操作,但不能让他们在pymongo工作。
你知道pymongo database.find操作应该返回以下字段和值吗
performance , abundance
10 0.9
9 0.7
使用
投影时
需要分别使用1
或0
和非True
或False
试试这个:
find( {'material_type':'solid',
'material.isotopes.atomic_number' : {'$eq': 6 }
},
{'_id' : 0, 'performance' : 1,
'material.isotopes.atomic_number.$' : 1 } )
返回:
{
"performance" : 10.0,
"material" : {
"isotopes" : [
{
"abundance" : 0.9,
"atomic_number" : 6.0
}
]
}
}
/* 2 */
{
"performance" : 9.0,
"material" : {
"isotopes" : [
{
"abundance" : 0.7,
"atomic_number" : 6.0
}
]
}
}
当所选文档中只需要一个特定数组元素时,可以在投影中使用$
。如果数组未嵌套,则可以尝试使用$elemMatch
然后,您可以将结果放入列表
,然后选择要打印的两个元素:
results = list( db.collection_name.find(
{'material_type':'solid',
'material.isotopes.atomic_number' : {'$eq': 6 }},
{'performance':1,
'material.isotopes.atomic_number.$':1 }
))
我正在运行pymongo 3.6.0和mongodb v3.6