如何在mongodb的对象数组搜索

假设mongodb文档(表)“用户”是

{
_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年被授予“国家奖章”的人

.在不同的年份可能还有其他人获得这个奖

我如何使用奖项类型和年份找到这个人。这样我就能得到准确的人。

271288 次浏览

正确的做法是:

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

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

如果没有$elemMatch, mongo将查找在某一年获得国家奖章的用户和在1975年获得国家奖章的用户,而不是在1975年获得国家奖章的用户。

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

使用$elemMatch来查找特定对象的数组

db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})

你可以通过两种方式做到这一点:

  1. ElementMatch - $elemMatch(如上述答案所解释)

    db.users.find({ awards: { $elemMatch: {award:'Turing Award', year:1977} } })

  2. 使用$andfind

    db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})

同样,要从整个数组中只返回一个字段,你可以使用projection来查找。并使用$

db.getCollection("sizer").find(
{ awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
{ "awards.$": 1, name: 1 }
);

将返回

{
_id: 1,
name: {
first: 'John',
last: 'Backus'
},
awards: [
{
award: 'National Medal',
year: 1975,
by: 'NSF'
}
]
}

我是MongoDb的新手,我有和Stennie描述的相同的问题。我试着在Compass中查询这个文档:

    {
"_id": 1,
"name": {
"first": "John",
"last": "Backus"
},
"birth": {
"$date": "1924-12-02T23:00:00.000Z"
},
"death": {
"$date": "2007-03-16T23:00:00.000Z"
},
"contribs": ["Fortran", "ALGOL", "Backus-Naur Form", "FP"],
"awards": [{
"award": "National Medal",
"year": 1975,
"by": "NSF"
}, {
"award": "Turing Award",
"year": 1977,
"by": "ACM"
}]
}

当对这个文档运行这个查询:{awards: {$elemMatch: {award:'National Medal', year:1975}}}时,我得到了相同的结果:

{
"_id": 1,
"name": {
"first": "John",
"last": "Backus"
},
"birth": {
"$date": "1924-12-02T23:00:00.000Z"
},
"death": {
"$date": "2007-03-16T23:00:00.000Z"
},
"contribs": ["Fortran", "ALGOL", "Backus-Naur Form", "FP"],
"awards": [{
"award": "National Medal",
"year": 1975,
"by": "NSF"
}, {
"award": "Turing Award",
"year": 1977,
"by": "ACM"
}]
}

可以通过这种方式获得所搜索的单个元素:

{
"_id": 1,
"name": {
"first": "John",
"last": "Backus"
},
"birth": {
"$date": "1924-12-02T23:00:00.000Z"
},
"death": {
"$date": "2007-03-16T23:00:00.000Z"
},
"contribs": ["Fortran", "ALGOL", "Backus-Naur Form", "FP"],
"awards": [{
"award": "National Medal",
"year": 1975,
"by": "NSF"
}, {}]

谢谢你!