【问题标题】:Pymongo find with a projection operatorPymongo 使用投影运算符查找
【发布时间】:2018-02-03 16:00:48
【问题描述】:

我有一个嵌套的 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

【问题讨论】:

    标签: python mongodb operators pymongo projection


    【解决方案1】:

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

    试试这个:

    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

    【讨论】:

    • 为什么10TrueFalse 更好?
    猜你喜欢
    • 2014-05-11
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多