Pymongo 使用投影运算符查找

Pymongo find with a projection operator

我有一个嵌套的 mongodb 数据库,我正在尝试执行查询以查找条目,并且 return 仅某些字段。

我想要 returning 的字段是嵌套的

数据库看起来像这样

 {
 '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,
                             }
                           ]
                }
 }

我想要 return 嵌套丰度字段,但 如果原子序数等于 6。

我已经尝试对查询执行投影,目前在 python pymongo

中有类似的东西
 results = database.find({'material_type':'solid'},
                         {'performance':True,
                          'material.isotopes':True 
                         })

我想我需要一个投影操作,但无法让它们在 pymongo 中工作。 pymongo database.find 操作应该对 return 以下字段和值有什么想法?

  performance , abundance 
  10              0.9
  9               0.7

当使用 projection 时,您需要分别使用 10 而不是 TrueFalse

试试这个:

find( {'material_type':'solid', 
      'material.isotopes.atomic_number' : {'$eq': 6 } 
      },
      {'_id' : 0, 'performance' : 1,  
      'material.isotopes.atomic_number.$' : 1 } )

Returns:

{
    "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
            }
        ]
    }
}

当您只需要 selected 文档中的一个特定数组元素时,您可以在 projection 中使用 $。如果您的数组未嵌套,您可以尝试 $elemMatch

然后您可以将结果放入 list,然后 select 您要打印的两个元素:

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