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

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

问题描述

假设 mongodb 文档(表)'users' 是

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

我想找到获得国家奖章"并且必须在1975年颁发的人可能还有其他人在不同的年份获得过这个奖项.

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.

如何使用奖励类型和年份找到此人.所以我可以得到确切的人.

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

推荐答案

正确的做法是:

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

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

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

如果没有 $elemMatch,mongo 会寻找在某个年份获得 National Medal 和在 1975 年获得一些奖项的用户,但不会寻找在 1975 获得 National Medal 的用户.

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

有关详细信息,请参阅 MongoDB $elemMatch 文档.有关使用数组查询文档的更多信息,请参阅阅读操作文档.

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

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

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