41
Write a MongoDB query to find the restaurants that have a grade with a score of 2 and a grade with a score of 6 and are located in the borough of Manhattan or Brooklyn, and their cuisine is not American.
没有什么难度
1db.restaurants.find({
2 $and: [
3 {borough: {$in: ["Manhattan", "Brooklyn"]}},
4 {"grades.score": {$all: [2, 6]}},
5 {cuisine: {$ne: "American"}}
6 ]
7})
这里用到了$all运算符, 表示后面的值[2,6]都要单独同时匹配
42
Write a MongoDB query to find the restaurants that have a grade with a score of 2 and a grade with a score of 6 and are located in the borough of Manhattan or Brooklyn, and their cuisine is not American or Chinese.
1db.restaurants.find({
2 $and: [
3{ borough: { $in: ["Manhattan", "Brooklyn"] } },
4{ cuisine: { $nin: ["American", "Chinese"] } },
5{ grades: { $elemMatch: { score: 2 } } },
6{ grades: { $elemMatch: { score: 6 } } }
7 ]
8})
43
Write a MongoDB query to find the restaurants that have a grade with a score of 2 or a grade with a score of 6.
1db.restaurants.find({
2 $or: [
3{ "grades.score": 2 },
4{ "grades.score": 6 }
5 ]
6})
44
Write a MongoDB query to find the restaurants that have a grade with a score of 2 or a grade with a score of 6 and are located in the borough of Manhattan.
没有什么难度
1db.restaurants.find({
2 $and: [
3 {
4 $or: [
5{ "grades.score": 2 },
6{ "grades.score": 6 }
7 ]
8 },
9{ "borough": "Manhattan" }
10 ]
11})
45
Write a MongoDB query to find the restaurants that have a grade with a score of 2 or a grade with a score of 6 and are located in the borough of Manhattan or Brooklyn.
1db.restaurants.find({
2 $and: [
3 {
4 $or: [
5{ borough: "Manhattan" },
6{ borough: "Brooklyn" }
7 ]
8 },
9 {
10 $or: [
11{ "grades.score": 2 },
12{ "grades.score": 6 }
13 ]
14 }
15 ]
16})
48
Write a MongoDB query to find the restaurants that have all grades with a score greater than 5.
这个是比较有意思的查询: 所有grade.score都要大于5
正确的查询数组里的值,都是存在,现在要转成\forall
1db.restaurants.find({
2 "grades": {
3 "$not": {
4 "$elemMatch": {
5 "score": {
6 "$lte": 5
7 }
8 }
9 }
10 }
11})
49
Write a MongoDB query to find the restaurants that have all grades with a score greater than 5 and are located in the borough of Manhattan.
多个条件,关键就在于这个条件:所有的
50
Write a MongoDB query to find the restaurants that have all grades with a score greater than 5 and are located in the borough of Manhattan or Brooklyn.
不难,这里有一个条件,或者
1db.restaurants.find({
2 "borough": {
3 "$in": ["Manhattan", "Brooklyn"]
4 },
5 "grades": {
6 "$not": {
7 "$elemMatch": {
8 "score": {
9 "$lte": 5
10 }
11 }
12 }
13 }
14})