1

采取以下措施。_id = 1我可以通过执行以下操作来提取匹配“1967”的记录。是否可以打印与 1967 年匹配的奖项和与“Penn”匹配的学校名称?

db.bios.find({_id:1, "awards.year" : 1967},{"awards.$":1}).pretty()


db.bios.insert(
    {
        _id: 1,
        awards: [
            {
                award: 'W.W. McDowell Award',
                year: 1967,
                by: 'IEEE Computer Society'
            },
            {
                award: 'National Medal of Science',
                year: 1975,
                by: 'National Science Foundation'
            },
         ],
         "schools" : [
             {
                name : "Harvard",
                year : 1945
             },
             {
                name : "Penn",
                year : 1950
             }
         ]
    }
)
4

1 回答 1

3

从 v2.2.2 开始,每个查询只能使用一个$位置运算符,但可以$elemMatch多次使用投影运算符来执行此操作:

db.bios.find({_id:1}, {
    awards: {$elemMatch: {year: 1967}}, 
    schools: {$elemMatch: {name: "Penn"}}
}).pretty()

输出:

{
  "_id": 1,
  "awards": [
    {
      "award": "W.W. McDowell Award",
      "year": 1967,
      "by": "IEEE Computer Society"
    }
  ],
  "schools": [
    {
      "name": "Penn",
      "year": 1950
    }
  ]
}
于 2013-01-14T02:26:14.327 回答