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

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

问题描述

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 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.

解决方案

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 the year 1975, 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天全站免登陆