mongodb 使用mongodb在数组中查找子文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19632850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find Subdocument in Array with mongodb
提问by mritz_p
I am playing around with the The bios Example Collection from http://docs.mongodb.org/manual/reference/bios-example-collectionto educate myself about querying mongodb.
我正在使用http://docs.mongodb.org/manual/reference/bios-example-collection 中的 bios 示例集合来教育自己查询 mongodb。
I want to retrieve informations about the awards won by _id : 1in year : 1975.
我想检索有关_id : 1在1975 年获得的奖项的信息。
I tried several queries, among those
我尝试了几个查询,其中
bios.find({
"_id" : 1,
"awards" : {
"year" : 1975
}
});
but I never receive the proper document back. How can I retrieve this document in the array?
但我从来没有收到正确的文件回来。如何在数组中检索此文档?
回答by mnemosyn
You have to use the dot notation:
您必须使用点符号:
bios.find({"_id" : 1, "awards.year" : 1975 });
It's a rather pointless query, because you also have the _id
in the query, but I guess that's due to the fact that you're playing with an example. Also, you're saying you're looking for awards from 1967, but the code says 1975.
这是一个相当无意义的查询,因为您_id
在查询中也有,但我想这是因为您正在玩一个例子。另外,您是说您正在寻找 1967 年的奖项,但代码显示是 1975 年。
If you search for "awards" : { "year" : 1975 }
, mongodb will look for an exact match of the entire subdocument awards
. In this case, that is not what you want. Also, since awards
is an array, this will always be false. If you wanted to look up a specific award document in a list, $elemMatch
would be the way to go.
如果您搜索"awards" : { "year" : 1975 }
,mongodb 将查找整个子文档的完全匹配awards
。在这种情况下,这不是您想要的。此外,由于awards
是一个数组,这将始终为假。如果您想在列表中查找特定的奖励文件,$elemMatch
这将是您要走的路。