Node.js Connect to MongoDB
MongoDB is a document-oriented database management system, written in C++.
In this chapter, we will introduce how to use Node.js to connect to MongoDB and perform database operations.
If you don't have basic knowledge of MongoDB yet, you can refer to our tutorial:MongoDB Tutorial。
Install Driver
This tutorial uses theTaobao-customized cnpm commandto install:
$ cnpm install mongodb
After successful installation, we can use the MongoClient object to connect to the database:
Example
const { MongoClient } = require('mongodb');
async function main() {
// MongoDB connection URI
const uri = "mongodb://localhost:27017"; // If you are using a remote MongoDB, please change the URI accordingly
// Create a new MongoClient
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
// Connect to the MongoDB server
await client.connect();
console.log("Connected successfully to server");
} finally {
// Make sure to close the connection when finished
await client.close();
}
}
main().catch(console.error);
Executing the above code produces the following output:
Connected successfully to server
Connection parameter description:
MongoClient: This is the MongoDB client, used to connect to the database.uri: This is the MongoDB connection string, in the formatmongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]。useNewUrlParseranduseUnifiedTopologyare some options used to avoid some old connection behaviors.
Next, we will implement the create, read, update, and delete (CRUD) functions.
Create Database
To create a database in MongoDB, we first need to create a MongoClient object, then configure the specified URL and port number.
If the database does not exist, MongoDB will create the database and establish the connection.
Create Connection
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collection = database.collection('exampleCollection');
const doc = { name: "Example", type: "Test" };
const result = await collection.insertOne(doc);
console.log(`New document created,IDis: ${result.insertedId}`);
} finally {
await client.close();
}
}
main().catch(console.error);
Executing the above code produces the following output:
成功连接到服务器
新文档已创建,ID 为: 6678e18e0bb3f4247be610d8
Create Collection
We can use the createCollection() method to create a collection:
Create Collection
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`Collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const doc = { name: "Example", type: "Test" };
const result = await collection.insertOne(doc);
console.log(`New document created,IDis: ${result.insertedId}`);
} finally {
await client.close();
}
}
main().catch(console.error);
Executing the above code produces the following output:
成功连接到服务器
集合 exampleCollection 创建成功
新文档已创建,ID 为: 6678e1b5c742b3ebd57f9759
Database Operations (CRUD)
Unlike MySQL, MongoDB automatically creates databases and collections, so we don't need to manually create them before use.
Insert Data
In the following example, we connect to the exampleCollection table in the example database and insert a piece of data, using insertOne():
Insert One Document
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`Collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const doc = { name: "Alice", age: 25, address: "Wonderland" };
const result = await collection.insertOne(doc);
console.log(`New document created,IDis: ${result.insertedId}`);
} finally {
await client.close();
}
}
main().catch(console.error);
Execute the following command, and the output result is:
成功连接到服务器
集合 exampleCollection 创建成功
新文档已创建,ID 为: 6678e1d1f9503dc2e0e2a20b
From the output result, the data has been inserted successfully.
We can also open the MongoDB client to view the data, such as:
> show dbs
example 0.000GB # 创建了 example 数据库
> use example # 切换到 example 数据库
example> show tables
exampleCollection # 创建了 exampleCollection 集合(数据表)
# 自动创建了 site 集合(数据表)
example> db.exampleCollection.find()
[
{
_id: ObjectId('6678e1d1f9503dc2e0e2a20b'),
name: 'Alice',
age: 25,
address: 'Wonderland'
}
]
If you want to insert multiple documents, you can useinsertMany():
Insert Multiple Documents
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`Collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new documents created,IDis:`);
Object.keys(result.insertedIds).forEach((key, index) => {
console.log(`Document ${index + 1}: ${result.insertedIds[key]}`);
});
} finally {
await client.close();
}
}
main().catch(console.error);
The execution output result is:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 6678e30e80ac30e5e689f13a
文档 2: 6678e30e80ac30e5e689f13b
文档 3: 6678e30e80ac30e5e689f13c
Query Data
You can use find() to search for data. find() can return all data matching the conditions.
If no conditions are specified, find() returns all data in the collection.
find()
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`Collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new documents created,IDis:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`Document ${index + 1}: ${id}`);
});
const query = {};
const options = { projection: { _id: 0, name: 1, age: 1, address: 1 } };
const cursor = collection.find(query, options);
const allValues = await cursor.toArray();
console.log("Queried documents:");
console.log(allValues);
} finally {
await client.close();
}
}
main().catch(console.error);
The execution output result is:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 0
文档 2: 1
文档 3: 2
查询到的文档:
[
{ name: 'Alice', age: 25, address: 'Wonderland' },
{ name: 'Bob', age: 30, address: 'Builderland' },
{ name: 'Charlie', age: 35, address: 'Chocolate Factory' }
]
The following example retrieves instances where name is "Alice":
Query Data with Specified Conditions
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`Collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new document(s) have been created,IDas: `);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`document ${index + 1}: ${id}`);
});
const query = { name: "Alice" };
const options = { projection: { _id: 0, name: 1, age: 1, address: 1 } };
const cursor = collection.find(query, options);
const allValues = await cursor.toArray();
console.log("Queried documents:");
console.log(allValues);
} finally {
await client.close();
}
}
main().catch(console.error);
The output after executing the following command is:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 0
文档 2: 1
文档 3: 2
查询到的文档:
[
{ name: 'Alice', age: 25, address: 'Wonderland' }
]
Update Data
We can also modify data in the database. The following example will update the data where name is 'Alice':
Update One Document
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new document(s) have been created,IDas: `);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`document ${index + 1}: ${id}`);
});
const filter = { name: "Alice" };
const updateDoc = {
$set: {
age: 28,
address: "New Wonderland"
},
};
const updateResult = await collection.updateOne(filter, updateDoc);
console.log(`${updateResult.matchedCount}document(s) matched the filter criteria`);
console.log(`${updateResult.modifiedCount}document(s) have been updated`);
const updatedDocument = await collection.findOne(filter);
console.log("Updated documents:");
console.log(updatedDocument);
} finally {
await client.close();
}
}
main().catch(console.error);
After successful execution, the output is as follows:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 0
文档 2: 1
文档 3: 2
1 个文档匹配筛选条件
1 个文档已更新
更新后的文档:
{
_id: new ObjectId('6678e1d1f9503dc2e0e2a20b'),
name: 'Alice',
age: 28,
address: 'New Wonderland'
}
If you want to update all documents that match the criteria, you can useupdateMany():
Update Multiple Documents
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Alice", age: 28, address: "Old Wonderland" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new document(s) have been created,IDas: `);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`document ${index + 1}: ${id}`);
});
const filter = { name: "Alice" };
const updateDoc = {
$set: {
address: "Updated Wonderland"
},
};
const updateResult = await collection.updateMany(filter, updateDoc);
console.log(`${updateResult.matchedCount}document(s) matched the filter criteria`);
console.log(`${updateResult.modifiedCount}document(s) have been updated`);
const updatedDocuments = await collection.find(filter).toArray();
console.log("Updated documents:");
console.log(updatedDocuments);
} finally {
await client.close();
}
}
main().catch(console.error);
Delete Data
The following example deletes the data where name is 'Alice':
Delete One Document
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new document(s) have been created,IDas: `);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`document ${index + 1}: ${id}`);
});
const filter = { name: "Alice" };
const deleteResult = await collection.deleteOne(filter);
console.log(`${deleteResult.deletedCount}document(s) have been deleted`);
const remainingDocuments = await collection.find({}).toArray();
console.log("Remaining documents:");
console.log(remainingDocuments);
} finally {
await client.close();
}
}
main().catch(console.error);
After successful execution, the output is:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 0
文档 2: 1
文档 3: 2
1 个文档已删除
剩余的文档:
[
{
_id: new ObjectId('6678e18e0bb3f4247be610d8'),
name: 'Example',
type: 'Test'
},
...
If you want to delete multiple documents, you can usedeleteMany()method
The following example deletes all data where type is 'en':
Delete Multiple Documents
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Alice", age: 28, address: "Old Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new document(s) have been created,IDas: `);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`document ${index + 1}: ${id}`);
});
const filter = { name: "Alice" };
const deleteResult = await collection.deleteMany(filter);
console.log(`${deleteResult.deletedCount}document(s) have been deleted`);
const remainingDocuments = await collection.find({}).toArray();
console.log("Remaining documents:");
console.log(remainingDocuments);
} finally {
await client.close();
}
}
main().catch(console.error);
Sort
Sorting uses the sort() method, which accepts one parameter to specify whether the order is ascending (1) or descending (-1).
For example:
{ type: 1 } // 按 type 字段升序
{ type: -1 } // 按 type 字段降序
Sort by type in ascending order:
Sorting
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" },
{ name: "Dave", age: 20, address: "Dreamland" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new document(s) have been created,IDas: `);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`document ${index + 1}: ${id}`);
});
const sortedDocsAsc = await collection.find().sort({ age: 1 }).toArray();
console.log("Documents sorted by the age field in ascending order:");
console.log(sortedDocsAsc);
const sortedDocsDesc = await collection.find().sort({ age: -1 }).toArray();
console.log("Documents sorted by the age field in descending order:");
console.log(sortedDocsDesc);
} finally {
await client.close();
}
}
main().catch(console.error);
Query Pagination
If you want to set the number of returned documents, you can uselimit()method, which accepts only one parameter specifying the number of documents to return.
limit(): Read Two Documents
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" },
{ name: "Dave", age: 20, address: "Dreamland" },
{ name: "Eve", age: 22, address: "Eden" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new document(s) have been created,IDas: `);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`document ${index + 1}: ${id}`);
});
const limitedDocs = await collection.find().limit(3).toArray();
console.log("Limit the query results to 3 documents:");
console.log(limitedDocs);
} finally {
await client.close();
}
}
main().catch(console.error);
If you want to specify the number of documents to skip, you can useskip()method.
The skip() method is used to skip a specified number of documents and return the query results of the remaining documents.
skip(): Skip the first two documents and read two documents
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('example');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`collection ${collectionName}created successfully`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" },
{ name: "Dave", age: 20, address: "Dreamland" },
{ name: "Eve", age: 22, address: "Eden" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}new document(s) have been created,IDas: `);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`document ${index + 1}: ${id}`);
});
const skippedDocs = await collection.find().skip(2).toArray();
console.log("Query results after skipping the first two documents:");
console.log(skippedDocs);
} finally {
await client.close();
}
}
main().catch(console.error);
Connection Operation
mongoDB is not a relational database, but we can use$lookupto implement left join.
$lookup is an aggregation pipeline operator in MongoDB used to perform left outer joins. It can be used to find documents in one collection that match the conditions in another collection and merge them together.
For example, we have two collections with data as follows:
Collection 1: orders
[
{ "_id": 1, "product_id": 101, "quantity": 2 },
{ "_id": 2, "product_id": 102, "quantity": 1 },
{ "_id": 3, "product_id": 103, "quantity": 4 }
]
Collection 2: products
[
{ "_id": 101, "name": "Product A", "price": 50 },
{ "_id": 102, "name": "Product B", "price": 70 },
{ "_id": 103, "name": "Product C", "price": 100 },
{ "_id": 104, "name": "Product D", "price": 120 }
]
Now we want to use the $lookup operation to associate the product_id field in the orders collection with the _id field in the products collection, and obtain detailed product information for each order.
The following is a MongoDB aggregation example that implements this functionality:
Example
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("Successfully connected to the server");
const database = client.db('mydatabase');
const ordersCollection = database.collection('orders');
const productsCollection = database.collection('products');
const pipeline = [
{
$lookup: {
from: 'products',
localField: 'product_id',
foreignField: '_id',
as: 'productDetails'
}
}
];
const result = await ordersCollection.aggregate(pipeline).toArray();
console.log("Left outer join query results:");
console.log(result);
} finally {
await client.close();
}
}
main().catch(console.error);
Drop Collection
We can usedrop()method to delete a collection:
drop()
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("example");
dbo.collection("test").drop(function(err, delOK) {
if (err) throw err;
if (delOK) console.log("Collection deleted");
db.close();
});
});
Using Promise
Promise is a class provided by ECMAScript 6, intended to write complex asynchronous tasks more elegantly.
If you don't understand Promise yet, you can refer toJavaScript Promise。
The following example uses Promise to create a collection:
Example
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
function connectDB() {
return new Promise((resolve, reject) => {
client.connect((err) => {
if (err) {
reject(err);
} else {
console.log("Successfully connected to the MongoDB server");
resolve(client.db());
}
});
});
}
connectDB()
.then(database => {
console.log("Successfully connected to the database");
console.log("Database name:", database.databaseName);
client.close();
})
.catch(err => {
console.error("An error occurred while connecting to the database:", err);
});
Promise Data Operations
Now let's implement four consecutive operations in one program: add, query, update, and delete.
Example
const { MongoClient, ObjectId } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
function connectDB() {
return new Promise((resolve, reject) => {
client.connect((err) => {
if (err) {
reject(err);
} else {
console.log("Successfully connected to the MongoDB server");
resolve(client.db());
}
});
});
}
function insertDocument(db, document) {
const collection = db.collection('documents');
return new Promise((resolve, reject) => {
collection.insertOne(document, (err, result) => {
if (err) {
reject(err);
} else {
console.log("Document added successfully");
resolve(result);
}
});
});
}
function findDocuments(db) {
const collection = db.collection('documents');
return new Promise((resolve, reject) => {
collection.find({}).toArray((err, docs) => {
if (err) {
reject(err);
} else {
console.log("Query documents result:");
console.log(docs);
resolve(docs);
}
});
});
}
function updateDocument(db, id, updatedValues) {
const collection = db.collection('documents');
return new Promise((resolve, reject) => {
collection.updateOne({ _id: ObjectId(id) }, { $set: updatedValues }, (err, result) => {
if (err) {
reject(err);
} else {
console.log("Document updated successfully");
resolve(result);
}
});
});
}
function deleteDocument(db, id) {
const collection = db.collection('documents');
return new Promise((resolve, reject) => {
collection.deleteOne({ _id: ObjectId(id) }, (err, result) => {
if (err) {
reject(err);
} else {
console.log("Document deleted successfully");
resolve(result);
}
});
});
}
async function performOperations() {
try {
const database = await connectDB();
const insertResult = await insertDocument(database, { name: "Document 1" });
const findResult = await findDocuments(database);
const updatedDocId = insertResult.insertedId;
const updateResult = await updateDocument(database, updatedDocId, { name: "Updated Document 1" });
const deleteResult = await deleteDocument(database, updatedDocId);
console.log("Final operation completed:");
console.log("Delete document result:", deleteResult);
} catch (err) {
console.error("An error occurred while performing the operation:", err);
} finally {
await client.close();
}
}
performOperations();
Execution result:
数据库已连接
[ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ]
[ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ]
[]
Other extensions