如何在mongodb中搜索对象数组 [英] How to search in array of object in mongodb

查看:749
本文介绍了如何在mongodb中搜索对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设mongodb文档(表格)'用户'是

  {
_id:1,
名称:{first:'John',last:'Backus'},
出生:新日期('Dec 03,1924'),
death:new Date('Mar 17,2007') ,
contribs:['Fortran','ALGOL','Backus-Naur Form','FP'],
奖励:[
{奖励:'国家奖章',
年:1975年,
by:'NSF'},
{奖:'图灵奖',
年:1977年,
by:'ACM'}
]
}
和其他对象(人)s

我想找获得国家奖章并且必须在1975年获奖的人
可能有其他人在不同年份获得此奖项。



怎么能我发现这个人使用奖励类型和年份。所以我可以得到确切的人。

解决方案

正确的方法是:

  db.users.find({awards:{$ elemMatch:{award:'National Medal',年份:1975}}})

$ elemMatch 允许您匹配同一数组元素中的多个组件。



没有 $ elemMatch mongo会在一年内寻找拥有国家奖章的用户,并在1975年代寻找一些奖励,但不会为1975年国家奖章。



参见 MongoDB $ elemMatch文档了解更多信息。有关使用数组查询文档的详细信息,请参阅读取操作文档。 / p>

Suppose the mongodb document(table) 'users' is

{
  _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 award 'Nation Medal' and must be awarded in year 1975 There could be other persons who have this award in different years.

How can I find this person using award type and year. So I can get exact person.

解决方案

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

这篇关于如何在mongodb中搜索对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆