我有以下文件:
{
"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.grade
和grades.score
的查询,如果grades
对象有grade == "A"
和score == 2
,则不会返回此文档。但是,如果一个grades
对象有grade == "A"
而另一个grades
对象有score == 2
,我希望它返回一个文档。
这也可以说明我正在尝试做什么(尽管它不起作用):
db.restaurants.find({
grades : {
$and: [
{"grade": {'$ne':"A"}},
{"score": {'$ne':2}}
]
}
});
答案 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