# 模块二 基础巩固 MongoDB 写入和查询

## 2.5.3 MongoDB -- 写入和查询 <a href="#id-253mongodb-xie-ru-he-cha-xun" id="id-253mongodb-xie-ru-he-cha-xun"></a>

* 写入
* 查询
* 查找操作符
* 逻辑操作符
* 其他
* 嵌套对象
* 数组
* 游标方法

### 写入 <a href="#xie-ru" id="xie-ru"></a>

<https://docs.mongodb.com/manual/tutorial/insert-documents/>

* insertOne
* insertMany

```
db.questions.insert( 
{  
    "_id":"003",
    "title":"第三个问题", 
    "view":0,
    "isDeleted":false,
    "content":"第三个问题", 
    "status":"open", 
    "tags":["c#"], 
    "answers":[
        {"content":"回答1"},
        {"content":"回答2"},
        {"content":"回答3"}
        ]
 } 
    )
```

```
db.questions.insertMany( 
[
{  
    "_id":"004",
    "title":"第三个问题", 
    "view":0,
    "isDeleted":false,
    "content":"第三个问题", 
    "status":"open", 
    "tags":["c#"], 
    "answers":[
        {"content":"回答1"},
        {"content":"回答2"},
        {"content":"回答3"}
        ]
 },
 {  
    "_id":"005",
    "title":"第三个问题", 
    "view":0,
    "isDeleted":false,
    "content":"第三个问题", 
    "status":"open", 
    "tags":["c#"], 
    "answers":[
        {"content":"回答1"},
        {"content":"回答2"},
        {"content":"回答3"}
        ]
 }
] 
    )
```

### 查询 <a href="#cha-xun" id="cha-xun"></a>

<https://docs.mongodb.com/manual/reference/operator/query/>

```
db.users.find(
    { age: { $gt: 18 } },    // 查询条件
    { name: 1, address: 1 }  // 查询字段
).limit(5)
```

```
db.getCollection('questions').find({"title":"第三个问题"},{"title":1,"content":1})

db.getCollection('questions').find({},{"title":1,"content":1}).skip(1).limit(2)
```

### 查找操作符 <a href="#cha-zhao-cao-zuo-fu" id="cha-zhao-cao-zuo-fu"></a>

| Name | Description |
| ---- | ----------- |
| $eq  | 等于          |
| $gt  | 大于          |
| $gte | 大于等于        |
| $lt  | 小于          |
| $lte | 小于等于        |
| $ne  | 不等于         |
| $in  | 存在于         |
| $nin | 不存在于：一般用于数组 |

```
// 大于等于
db.getCollection('questions').find({"view":{$gte: NumberInt(0)}})

// 存在于
db.getCollection('questions').find({"tags":{$in: ["c#"]}})
```

### 逻辑操作符 <a href="#luo-ji-cao-zuo-fu" id="luo-ji-cao-zuo-fu"></a>

| Name | Description |
| ---- | ----------- |
| $and | 满足多个条件      |
| $or  | 满足多个条件中的一个  |
| $not | 不匹配，或者字段不存在 |
| $nor | 多个条件，一个都不满足 |

```
// 满足多个条件中的一个
db.getCollection('questions').find({$or:
[
{"tags":{$in: ["c#"]}},
{"view":{$gt:2}}
]
})

db.getCollection('questions').find({"view":{"$gt": 5}})
// 不匹配，或者字段不存在（取反）
db.getCollection('questions').find({"view": {$not: {"$gt": 5}}})

// 多个条件，一个都不满足
db.getCollection('questions').find({$nor: [{"view":{"$gt": 5}}]})
```

### 其他 <a href="#qi-ta" id="qi-ta"></a>

| Name    | Description |
| ------- | ----------- |
| $exists | 存在某个字段      |
| $type   | 字段的类型       |

```
// 存在某个字段则显示
db.getCollection('questions').find({"best": {$exists:1}})
// 不存在某个字段则显示
db.getCollection('questions').find({"best": {$exists:0}})
// 字段的类型，16代表32-byte integer
db.getCollection('questions').find({"view": {$type: 16}})
```

<https://mongoing.com/docs/reference/bson-types.html>

### 嵌套对象 <a href="#qian-tao-dui-xiang" id="qian-tao-dui-xiang"></a>

```
db.getCollection('questions').find({"best.content":{$eq: "最好的答案"}})
```

### 数组 <a href="#shu-zu" id="shu-zu"></a>

| Name       | Description     |
| ---------- | --------------- |
| $all       | 所有元素匹配，匹配简单类型数组 |
| $elemMatch | 用于匹配 object 数组  |
| $size      | 长度条件            |

```
db.getCollection('questions').find({"tags": {$in: ["c#"]}})

db.getCollection('questions').find({"tags": {$nin: ["c#"]}})

// 都必须包含
db.getCollection('questions').find({"tags": {$all: ["c#", "asp.net core"]}})

// 大小为2
db.getCollection('questions').find

// 包含 回答1 的数组
db.getCollection('questions').find({"answers": {$elemMatch: {"content": "回答1"}}})

db.getCollection('questions').find({"answers": {$elemMatch: {"content": {$gte: "回答1"}}}})
```

### 游标方法 <a href="#you-biao-fang-fa" id="you-biao-fang-fa"></a>

只在 mongo shell 中有效，其他语言版本 sdk 无效

* skip
* limit
* count
* pretty 美化
