根据映射中键的存在性有选择地检索

huangapple go评论98阅读模式
英文:

Selectively retrieving depending on existence of key in map

问题

在mongodb中,是否可以根据映射中键的存在性有选择地检索数据?如果可以,如何操作?

假设我有一个文档,例如:

{ " _id ":1234,
    " parentfield1 ":{
        " childfield1 ":{ ...},
        " childfield2 ":{ ...},
        " childfield5 ":{ ...},//可能有很多childfields.. > 50
    },
}

我如何能够有选择地从文档中检索出一些特定的childfields,给出多个选择的选项?其中一些可能在文档中不存在。

输入 " childfield1 "," childfield2 "," childfield3 "

-> 输出

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

这是否可行?是否还可以高效地实现?任何帮助都将是很好的(使用python、go)。

英文:

Is it possible to selectively retrieve depending on the existence of keys in a map in mongodb? And if so, how do you go about doing it?

Suppose I have a document that looks like this for example..

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

How would I be able to selectively retrieve from the document a/some particular childfields given multiple options to choose from? Some of which may not exist in the document.

i.e.

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

-> output 

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

Is it even doable? Is it possible to do efficiently also?
Any help would be great (python, go).

答案1

得分: 0

是的,这就是findprojection参数的目的:

<!-- language: lang-js -->

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

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

如果你希望projection参数对象是动态的,可以通过编程的方式构建它。

英文:

Yes, that's the purpose of the projection parameter of find:

<!-- language: lang-js -->

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

If a specified field isn't present in a given doc, the other matching fields will still be included.

Build up the projection parameter object programmatically if you want it to be dynamic.

huangapple
  • 本文由 发表于 2013年2月9日 00:18:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/14776879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定