具有特定条件的MongoDB find()

时间:2018-11-28 21:30:16

标签: mongodb nosql

假设我有两个人,他们都获得了国家科学奖章和其他奖项。我想知道是谁在1980年以后获得了美国国家科学奖章。所以我尝试了

db.scientists.find({$and: [
        {
            "awards.award": "National Medal of Science"
        },
        {
            "awards.year": {$gt: 1980
            }
        }
    ]
});   

并返回两位科学家的名字。我想我的问题是如何将条件应用于MongoDB中的条件。对不起,我的英语不好。谢谢。

"name" : {
    "first" : "John", 
    "last" : "Backus"
}, 

"awards" : [
    {
        "award" : "W.W. McDowell Award", 
        "year" : 1967.0, 
        "by" : "IEEE Computer Society"
    }, 
    {
        "award" : "National Medal of Science", 
        "year" : 1975.0, 
        "by" : "National Science Foundation"
    }, 
    {
        "award" : "Turing Award", 
        "year" : 1977.0, 
        "by" : "ACM"
    }, 
    {
        "award" : "Draper Prize", 
        "year" : 1993.0, 
        "by" : "National Academy of Engineering"
    }
]




"name" : {
    "first" : "John", 
    "last" : "McCarthy"
}, 

"awards" : [
    {
        "award" : "Turing Award", 
        "year" : 1971.0, 
        "by" : "ACM"
    }, 
    {
        "award" : "Kyoto Prize", 
        "year" : 1988.0, 
        "by" : "Inamori Foundation"
    }, 
    {
        "award" : "National Medal of Science", 
        "year" : 1990.0, 
        "by" : "National Science Foundation"
    }
]

2 个答案:

答案 0 :(得分:0)

您应该使用elemMatch;

db.scientists.find({
    awards: {
        $elemMatch: {
            award: "National Medal of Science",
            year: { $gt: 1980 }
        }
    }
}); 

应该可以解决问题

Breif解释

MongoDB会整体搜索数组,因此它会为您提供结果;

包含的任何数组;

  • 具有“奖项”的元素:“国家科学奖章”
  • 带有'year'的元素:{$ gt:1980}

$elemMatch通过强制基于元素的匹配来解决此问题。 不太直观

答案 1 :(得分:-1)

通常JSON文档相互嵌套。这意味着一个键引用了另一个键值哈希。同样在这种情况下,MongoDB也提供了基于存储在嵌套JSON结构中的值搜索文档的可能性:

{ 
  "_id": ObjectId ("568c28fffc4be30d44d039aa"), 
  "firstname": "Max", 
  "lastname": "Mustermann", 
  "email": "m.mustermann@example.com", 
  "password": "d9729feb74992cc3482b350163a1a010, 
  " last_login ":" 2015-01-07 ", 
  " note ":" Always pays in time, very good customer! ", 
  " address ": 
  { 
    " country ":" Germany ", 
    " street ":" Beispielstrasse 64 ", 
    " zip ":" 62717 " 
  } 
}