Javascript 如何在mongodb中搜索对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14040562/
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
How to search in array of object in mongodb
提问by vcxz
Suppose the mongodb document(table) 'users' is
假设 mongodb 文档(表)'users' 是
{
_id: 1,
name: { first: 'John', last: 'Backus' },
birth: new Date('Dec 03, 1924'),
death: new Date('Mar 17, 2007'),
contribs: [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
awards: [
{ award: 'National Medal',
year: 1975,
by: 'NSF' },
{ award: 'Turing Award',
year: 1977,
by: 'ACM' }
]
}
and other object(person)s
I want to find the person who has the award 'National Medal' and must be awarded in year 1975 There could be other persons who have this award in different years.
我想找到获得“国家奖章”奖并且必须在1975年颁发的人。可能有其他人在不同的年份获得过这个奖项。
How can I find this person using award type and year. So I can get exact person.
我如何使用奖励类型和年份找到此人。所以我可以得到确切的人。
回答by Leonid Beschastny
The right way is:
正确的方法是:
db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})
$elemMatchallows you to match more than one component within the same array element.
$elemMatch允许您在同一数组元素中匹配多个组件。
Without $elemMatchmongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.
没有$elemMatchmongo 会寻找某年有国家奖章的用户,1975 年代有一些奖项,但不会寻找 1975 年有国家奖章的用户。
See MongoDB $elemMatch Documentationfor more info. See Read Operations Documentationfor more information about querying documents with arrays.
有关更多信息,请参阅MongoDB $elemMatch 文档。有关使用数组查询文档的更多信息,请参阅阅读操作文档。
回答by KARTHIKEYAN.A
Use $elemMatchto find the array of particular object
使用$elemMatch查找特定对象的数组
db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})

