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

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

Selectively retrieving depending on existence of key in map

问题

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

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

  1. { " _id "1234
  2. " parentfield1 ":{
  3. " childfield1 ":{ ...},
  4. " childfield2 ":{ ...},
  5. " childfield5 ":{ ...},//可能有很多childfields.. > 50
  6. },
  7. }

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

  1. 输入 " childfield1 "" childfield2 "" childfield3 "
  2. -> 输出
  3. { " _id "1234
  4. " parentfield1 ":{
  5. " childfield1 ":{ ... },
  6. " childfield2 ":{ ... },
  7. },
  8. }

这是否可行?是否还可以高效地实现?任何帮助都将是很好的(使用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..

  1. { "_id": 1234,
  2. "parentfield1" : {
  3. "childfield1" : { ...},
  4. "childfield2" : { ...},
  5. "childfield5" : { ...}, // There might be many childfields.. > 50
  6. },
  7. }

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.

  1. input "childfield1", "childfield2", "childfield3"
  2. -> output
  3. { "_id": 1234,
  4. "parentfield1": {
  5. "childfield1" : { ... },
  6. "childfield2" : { ... },
  7. },
  8. }

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

答案1

得分: 0

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

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

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

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

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

英文:

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

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

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

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:

确定