我有一个嵌套的mongodb数据库,我试图执行一个查询,该查询查找条目并仅返回某些字段。
我想返回的字段是嵌套的
数据库看起来像这样
{
'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
使用a时,projection
您需要分别使用1
or0
和notTrue
或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
}
]
}
}
您可以使用$
的projection
时候,你只需要在选取的文件一个特定的数组元素。您可以尝试$elemMatch
是否不嵌套数组。
然后,您可以将结果放入中list
,然后选择要打印的两个元素:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句