英文:
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
是的,这就是find
的projection
参数的目的:
<!-- language: lang-js -->
db.collection.find({_id: 1234}, {
'parentfield1.childfield1': 1,
'parentfield1.childfield2': 1,
'parentfield1.childfield3': 1
});
如果指定的字段在给定的文档中不存在,其他匹配的字段仍然会被包含在内。
如果你希望projection
参数对象是动态的,可以通过编程的方式构建它。
英文:
Yes, that's the purpose of the projection
parameter of find
:
<!-- language: lang-js -->
db.collection.find({_id: 1234}, {
'parentfield1.childfield1': 1,
'parentfield1.childfield2': 1,
'parentfield1.childfield3': 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论