这是一个非常简单的问题,我搜索了一切,但无法找到答案
我所拥有的只是
{
"_id" : 1,
"name" : {
"first" : "John",
"last" : "Backus"
},
"awards" : [
{
"award" : "W.W. McDowell Award",
**"year" : 1967,**
"by" : "IEEE Computer Society"
},
{
"award" : "Draper Prize",
**"year" : 1967,**
"by" : "National Academy of Engineering"
},
{
"award" : "National Medal of Science",
"year" : 1975,
"by" : "National Science Foundation"
}
]
},
{
"_id" : 2,
"name" : {
"first" : "John",
"last" : "McCarthy"
},
"awards" : [
{
"award" : "Turing Award",
"year" : 1971,
"by" : "ACM"
},
{
"award" : "Kyoto Prize",
**"year" : 1967,**
"by" : "Inamori Foundation"
},
{
"award" : "National Medal of Science",
"year" : 1990,
"by" : "National Science Foundation"
}
]
},
我所需要的只是1967年赢得的所有奖项!
我尝试了db.bios.find({"awards.year":1967},{award.$}).pretty()
我只得到
"_id" : 1,
"awards" : [
{
"award" : "W.W. McDowell Award",
"year" : 1967,
"by" : "IEEE Computer Society"
},
],
但我需要在所有文件中找到(第一个有两个如此完全3个像
{
"_id" : 1,
"awards" : [
{
"award" : "W.W. McDowell Award",
"year" : 1967,
"by" : "IEEE Computer Society"
},
{
"award" : "Draper Prize",
**"year" : 1967,**
"by" : "National Academy of Engineering"
}
]
},
{
"_id" : 2,
"award":[{
"award" : "Kyoto Prize",
"year" : 1967,
"by" : "Inamori Foundation"
}
]
}
我尝试使用$all
但无法获得结果。我希望我清楚
是的,我正在使用bios示例。
这一定非常简单,我会变得很短暂
请帮忙。
答案 0 :(得分:1)
您必须使用aggregation framework,因为$
仅指第一场比赛。在您的情况下,以下可能有效:
db.bios.aggregate( [
{ $match : {"awards.year":1967} },
{ $unwind : "$awards"},
{ $match : {"awards.year" :1967} }
]);
屈服
{
"_id" : 1,
"name" : {
"first" : "John",
"last" : "Backus"
},
"awards" : {
"award" : "W.W. McDowell Award",
"year" : 1967,
"by" : "IEEE Computer Society"
}
}
{
"_id" : 1,
"name" : {
"first" : "John",
"last" : "Backus"
},
"awards" : {
"award" : "Draper Prize",
"year" : 1967,
"by" : "National Academy of Engineering"
}
}
{
"_id" : 2,
"name" : {
"first" : "John",
"last" : "McCarthy"
},
"awards" : {
"award" : "Kyoto Prize",
"year" : 1967,
"by" : "Inamori Foundation"
}
}
正如您所看到的,这将复制文档的其余部分(因此John Backus的文档会被返回两次),但您可以通过添加$group
来更改它,例如
db.bios.aggregate( [ { $match : {"awards.year":1967} },
{ $unwind : "$awards"},
{ $match : {"awards.year" :1967} },
{ $group : { _id : "$_id", "awards" : { $push : "$awards" } } }
]).pretty();
但是有很多方法可以做到这一点,所以我建议您深入了解文档以获得所需的投影。