【进阶】MongoDB的基本操作与数据处理
发布时间: 2024-06-27 17:14:13 阅读量: 5 订阅数: 17 ![](https://csdnimg.cn/release/wenkucmsfe/public/img/col_vip.0fdee7e1.png)
![](https://csdnimg.cn/release/wenkucmsfe/public/img/col_vip.0fdee7e1.png)
![【进阶】MongoDB的基本操作与数据处理](https://pronteff.com/wp-content/uploads/2022/08/What-is-the-Aggregation-pipeline-in-MongoDB.png)
# 2.1 CRUD操作
### 2.1.1 创建和插入数据
MongoDB中创建和插入数据可以通过`insertOne()`和`insertMany()`方法。`insertOne()`方法用于插入单个文档,而`insertMany()`方法用于插入多个文档。
```javascript
// 插入单个文档
db.collection('users').insertOne({
name: 'John Doe',
age: 30
});
// 插入多个文档
db.collection('users').insertMany([
{ name: 'Jane Doe', age: 25 },
{ name: 'Bob Smith', age: 40 }
]);
```
# 2. MongoDB数据操作
### 2.1 CRUD操作
CRUD(Create、Read、Update、Delete)操作是数据库系统中最基本的四种操作,MongoDB也不例外。
#### 2.1.1 创建和插入数据
在MongoDB中,创建和插入数据使用`insertOne()`和`insertMany()`方法。
```js
// 插入单个文档
db.collection.insertOne({ name: "John Doe", age: 30 });
// 插入多个文档
db.collection.insertMany([
{ name: "Jane Doe", age: 25 },
{ name: "Peter Parker", age: 20 }
]);
```
#### 2.1.2 读取数据
读取数据使用`find()`方法,它返回一个游标对象,可以迭代遍历文档。
```js
// 查找所有文档
db.collection.find({}).forEach(doc => console.log(doc));
// 查找满足特定条件的文档
db.collection.find({ age: { $gt: 25 } }).forEach(doc => console.log(doc));
```
#### 2.1.3 更新数据
更新数据使用`updateOne()`和`updateMany()`方法,它们更新单个或多个文档。
```js
// 更新单个文档
db.collection.updateOne({ name: "John Doe" }, { $set: { age: 31 } });
// 更新多个文档
db.collection.updateMany({ age: { $gt: 25 } }, { $inc: { age: 1 } });
```
#### 2.1.4 删除数据
删除数据使用`deleteOne()`和`deleteMany()`方法,它们删除单个或多个文档。
```js
// 删除单个文档
db.collection.deleteOne({ name: "John Doe" });
// 删除多个文档
db.collection.deleteMany({ age: { $gt: 25 } });
```
### 2.2 查询操作
MongoDB提供了丰富的查询操作,包括基本查询、高级查询和聚合操作。
#### 2.2.1 基本查询
基本查询使用查询运算符,如`$eq`(等于)、`$gt`(大于)和`$in`(包含)。
```js
// 查找年龄为30的文档
db.collection.find({ age: 30 });
// 查找年龄大于25的文档
db.collection.find({ age: { $
```
0
0
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)