没有给定条目的MongoDB查询文档?

时间:2017-03-22 22:42:06

标签: mongodb

我有以下文件:

{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}

我想要一个查看grades.gradegrades.score的查询,如果grades对象有grade == "A"score == 2,则不会返回此文档。但是,如果一个grades对象有grade == "A"而另一个grades对象有score == 2,我希望它返回一个文档。

这也可以说明我正在尝试做什么(尽管它不起作用):

db.restaurants.find({
    grades : {
        $and: [
            {"grade": {'$ne':"A"}}, 
            {"score": {'$ne':2}}
        ]
    }
});  

1 个答案:

答案 0 :(得分:1)

您可以尝试以下查询。

您基本上需要$and $or$nand。 MongoDB没有$nand运算符,因此我将其替换为等效的运算。

db.restaurants.find({
    $and: [{
        $or: [{
            "grades.grade": "A"
        }, {
            "grades.score": 2
        }]
    }, {
        $nor: [{
            $and: [{
                "grades.grade": "A"
            }, {
                "grades.score": 2
            }]
        }]
    }]
});

$or操作将匹配任何成绩嵌入文档的成绩A或得分为2的所有文档。

{ "grade": "A", "score": 3 } --- Just grade A

{ "grade": "A", "score": 2 } --- Both grade A and score 2

{ "grade": "B", "score": 2 } --- Just score 2

$nand操作将匹配所有文档,其中没有任何成绩嵌入文档的成绩均为A且得分为2

{ "grade": "A", "score": 3 } --- Just grade A

{ "grade": "B", "score": 2 } --- Just score 2

{ "grade": "C", "score": 4 } --- None
以上操作的{p> $and是交集。

{ "grade": "A", "score": 3 } --- Just grade A

{ "grade": "B", "score": 2 } --- Just score 2