mongodb隐式创建集合demo
时间: 2023-05-22 07:04:45 浏览: 82
很高兴回答你的问题。MongoDB 会在第一次向一个尚不存在的集合中插入文档时自动创建该集合,这被称为隐式创建集合。下面是一个简单的 MongoDB 隐式创建集合的示例:
1. 连接 MongoDB 数据库
```javascript
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("mydb").collection("testCollection");
// perform actions on the collection object
client.close();
});
```
2. 插入文档并隐式创建集合
```javascript
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("mydb").collection("testCollection");
// insert document and implicitly create collection
collection.insertOne({ name: "John", age: 25 }, function(err, res) {
console.log("Document inserted");
client.close();
});
});
```
希望这可以帮助你理解 MongoDB 隐式创建集合的示例,如果你还有其它问题,可以继续问我。