【问题标题】:Selectively retrieving depending on existence of key in map根据地图中键的存在选择性检索
【发布时间】:2013-01-24 11:21:31
【问题描述】:

是否可以根据 mongodb 中映射中键的存在来选择性地检索?如果是这样,你会怎么做?

假设我有一个看起来像这样的文档..

{ "_id": 1234,
    "parentfield1" : {
        "childfield1" : { ...},
        "childfield2" : { ...},
        "childfield5" : { ...}, // There might be many childfields.. > 50
    },
} 

如果有多个选项可供选择,我如何能够有选择地从文档中检索一个/某些特定的子字段?其中一些可能在文档中不存在。

input "childfield1", "childfield2", "childfield3"

-> output 

{ "_id": 1234,
  "parentfield1": {
      "childfield1" : { ... },
      "childfield2" : { ... },
  },
}

它甚至可行吗?是否也可以有效地做? 任何帮助都会很棒(python,去)。

【问题讨论】:

    标签: python mongodb go querying


    【解决方案1】:

    是的,这就是findprojection参数的用途:

    db.collection.find({_id: 1234}, {
        'parentfield1.childfield1': 1,
        'parentfield1.childfield2': 1,
        'parentfield1.childfield3': 1
    });
    

    如果给定文档中不存在指定字段,则仍会包含其他匹配字段。

    如果您希望 projection 参数对象是动态的,请以编程方式构建它。

    【讨论】:

      猜你喜欢
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      相关资源
      最近更新 更多