MongoDB 练习 2

2025-09-09 00:00    #MongoDB   #Exercises  

21

Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants which prepared dish except ‘American’ and ‘Chinees’ or restaurant’s name begins with letter ‘Wil’.

1db.restaurants.find({
2    $or : [
3      {"name": /^Wil/},
4      {"cuisine" : { $nin :["American ","Chinees"] }}
5    ]
6  })

这两个写法是一样的

 1db.restaurants.find(
 2{$or: [
 3  {name: /^Wil/},
 4  {"$and": [
 5       {"cuisine" : {$ne :"American "}},
 6       {"cuisine" : {$ne :"Chinees"}}
 7   ]}
 8]}
 9,{"restaurant_id" : 1,"name":1,"borough":1,"cuisine" :1}
10);

22

  1. Write a MongoDB query to find the restaurant Id, name, and grades for those restaurants which achieved a grade of “A” and scored 11 on an ISODate “2014-08-11T00:00:00Z” among many of survey dates.

达到了 grade A 且 scored 11. 首先,我们要理解这里的意思到底是什么意思?

有三个条件:

这里的关键在于,数组grades其中的一条满足这3个条件.那么里这里要用到的$elemMatch

1db.restaurants.find({
2    grades:{ $elemMatch : { grade:'A',date:ISODate("2014-08-11T00:00:00Z"), scored: 11}}
3  })

但是给出的答案是,理解我写在注释里

1db.restaurants.find(
2    { // 这里是and
3      "grades.date": ISODate("2014-08-11T00:00:00Z"), // 这里只要有一个数组的元素成立
4      "grades.grade":"A" , // 这里只要有一个数组的元素成立
5      "grades.score" : 11// 这里只要有一个数组的元素成立
6    },
7      {"restaurant_id" : 1,"name":1,"grades":1}
8    );

这里怎么用数学描述: 设集合A为A = [{},{},{},{}], 满足条件aAbAcAa \in A \land b \in A \land c \in A

23

Write a MongoDB query to find the restaurant Id, name and grades for those restaurants where the 2nd element of grades array contains a grade of “A” and score 9 on an ISODate “2014-08-11T00:00:00Z”.

arrayElemAt(如果你需要明确选择数组中的特定元素)

如果你明确只想要查询数组的第二个元素,elemMatch 不能直接做这件事。不过,你可以结合 $arrayElemAt 来选择数组中的第二个元素进行条件匹配:

1db.collection.find({
2  "$expr": {
3    "$eq": [
4      { "$arrayElemAt": ["$grades", 1] },  // 获取第二个元素
5      { "grade": "A", "score": 9, "date": ISODate("2014-08-11T00:00:00Z") }  // 条件
6    ]
7  }
8})

那么还是官方给的答案比较简单:

1db.restaurants.find(
2                      { "grades.1.date": ISODate("2014-08-11T00:00:00Z"),
3                        "grades.1.grade":"A" ,
4                        "grades.1.score" : 9
5                      },
6                       {"restaurant_id" : 1,"name":1,"grades":1}
7                   );

24

Write a MongoDB query to find the restaurant Id, name, address and geographical location for those restaurants where 2nd element of coord array contains a value which is more than 42 and upto 52.

没有争议

1db.restaurants.find(
2                      {
3                        "address.coord.1": {$gt : 42, $lte : 52}
4                      },
5                        {"restaurant_id" : 1,"name":1,"address":1,"coord":1}
6                   );

25,26

就是排序而已

1db.restaurants.find().sort({"name":1});
2db.restaurants.find().sort( {"name":-1});

27

Write a MongoDB query to arranged the name of the cuisine in ascending order and for that same cuisine borough should be in descending order.

还是排序,不过同时要排序两个元素

1db.restaurants.find().sort(
2                           {"cuisine":1,"borough" : -1,}
3                          );

28

Write a MongoDB query to know whether all the addresses contains the street or not.

查询元素的存在性

1db.restaurants.find( {"address.street" : { $exists : true } } );

29

Write a MongoDB query which will select all documents in the restaurants collection where the coord field value is Double.

查询元素的类型

对于 field 为数组的文档,$type 返回的文档中至少有一个数组元素与传递给 $type 的类型匹配。

对 $type: “array” 的查询会返回字段本身为数组的文档。

$type — MongoDB 手册 v8.0

1db.restaurants.find( {"address.coord" : {$type : 1} });

30

Write a MongoDB query which will select the restaurant Id, name and grades for those restaurants which returns 0 as a remainder after dividing the score by 7.

这里用到了 $mod - MongoDB 手册 v8.0

1db.restaurants.find(
2                      {"grades.score" :
3                         {$mod : [7,0]}
4                      },
5                         {"restaurant_id" : 1,"name":1,"grades":1}
6                    );

31

Write a MongoDB query to find the restaurant name, borough, longitude and attitude and cuisine for those restaurants which contains ‘mon’ as three letters somewhere in its name.

正则查询

 1db.restaurants.find(
 2                   { name :
 3                     { $regex : "mon.*", $options: "i" }
 4                   },
 5                       {
 6                         "name":1,
 7                         "borough":1,
 8                         "address.coord":1,
 9                         "cuisine" :1
10                        }
11                   );

32

Write a MongoDB query to find the restaurant name, borough, longitude and latitude and cuisine for those restaurants which contain ‘Mad’ as first three letters of its name.

正则查询

 1db.restaurants.find(
 2                   { name :
 3                     { $regex : /^Mad/i, }
 4                   },
 5                       {
 6                         "name":1,
 7                         "borough":1,
 8                         "address.coord":1,
 9                         "cuisine" :1
10                        }
11                   );

33

Write a MongoDB query to find the restaurants that have at least one grade with a score of less than 5.

数组查询

1db.restaurants.find({ "grades.score": { $lt: 5 } })

34

Write a MongoDB query to find the restaurants that have at least one grade with a score of less than 5 and that are located in the borough of Manhattan.

怎么变简单了?

1db.restaurants.find({ "grades.score": { $lt: 5 }, "borough": "Manhattan" })

35

Write a MongoDB query to find the restaurants that have at least one grade with a score of less than 5 and that are located in the borough of Manhattan or Brooklyn.

还是简单

 1db.restaurants.find({
 2  $and: [
 3    {
 4      $or: [ // 可以用$in
 5        {borough: "Manhattan"},
 6        {borough: "Brooklyn"}
 7      ]
 8    },
 9    {
10      "grades.score": { $lt: 5 }
11    }
12  ]
13})

36

Write a MongoDB query to find the restaurants that have at least one grade with a score of less than 5 and that are located in the borough of Manhattan or Brooklyn, and their cuisine is not American.

官方给的这个答案,可以不用最外层的$and

1db.restaurants.find({
2  $and: [
3{ $or: [{ borough: "Manhattan" }, { borough: "Brooklyn" }] },
4{ "grades.score": { $lt: 5 } },
5{ cuisine: { $ne: "American" } }
6  ]
7})

37

Write a MongoDB query to find the restaurants that have at least one grade with a score of less than 5 and that are located in the borough of Manhattan or Brooklyn, and their cuisine is not American or Chinese.

这里用到了不是...,也不是....这个也语法

$nor - MongoDB 手册 v8.0

选择数组中所有查询谓词均未通过的文档

1$nor :[ expr1 ,expr2...]

那么查询的文档满足的条件是:

1expr1(doc1) == false and expr2(doc2) == false

38

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.

grades 含有2,和6

我写的

1db.restaurants.find({
2    "grades.score": 2,
3    "grades.score": 6,
4  })

效果一样的官方答案。

1db.restaurants.find({
2  $and: [
3    {"grades.score": 2},
4    {"grades.score": 6}
5  ]
6})

39

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.

没有什么难度

1db.restaurants.find({
2  $and: [
3    {"grades.score": 2},
4    {"grades.score": 6},
5    {"borough": "Manhattan"}
6  ]
7})

40

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.

1db.restaurants.find({
2  $and: [
3    {"grades.score": 2},
4    {"grades.score": 6},
5    {"borough": {"$in": ["Manhattan", "Brooklyn"]}}
6  ]
7})