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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Here you can perform database operations, such as creating a collection or inserting documents 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 { //Make sure to close the connection when finished 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Use the createCollection method to create a collection const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`Collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create a new document const doc = { name: "Example", type: "Test" }; //Insert a document into the collection const result = await collection.insertOne(doc); console.log(`New document created,IDis: ${result.insertedId}`); } finally { //Make sure to close the connection when finished 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Use the createCollection method to create a collection const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`Collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create a new document const doc = { name: "Alice", age: 25, address: "Wonderland" }; //Insert a document into the collection const result = await collection.insertOne(doc); console.log(`New document created,IDis: ${result.insertedId}`); } finally { //Make sure to close the connection when finished 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Use the createCollection method to create a collection const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`Collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents const docs = [ { name: "Alice", age: 25, address: "Wonderland" }, { name: "Bob", age: 30, address: "Builderland" }, { name: "Charlie", age: 35, address: "Chocolate Factory" } ]; //Insert multiple documents into the collection 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 { //Make sure to close the connection when finished 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Use the createCollection method to create a collection const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`Collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents const docs = [ { name: "Alice", age: 25, address: "Wonderland" }, { name: "Bob", age: 30, address: "Builderland" }, { name: "Charlie", age: 35, address: "Chocolate Factory" } ]; //Insert multiple documents into the collection 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}`); }); //Query all documents in the collection const query = {}; //An empty query object means query all documents const options = { projection: { _id: 0, name: 1, age: 1, address: 1 } }; //Only select the required fields const cursor = collection.find(query, options); //Print all queried documents const allValues = await cursor.toArray(); console.log("Queried documents:"); console.log(allValues); } finally { //Make sure to close the connection when finished 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Use the createCollection method to create a collection const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`Collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents const docs = [ { name: "Alice", age: 25, address: "Wonderland" }, { name: "Bob", age: 30, address: "Builderland" }, { name: "Charlie", age: 35, address: "Chocolate Factory" } ]; //Insert multiple documents into the collection 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}`); }); //Query documents using the name parameter const query = { name: "Alice" }; //Search criteria const options = { projection: { _id: 0, name: 1, age: 1, address: 1 } }; //Select only the required fields const cursor = collection.find(query, options); //Print the queried documents const allValues = await cursor.toArray(); console.log("Queried documents:"); console.log(allValues); } finally { //Make sure to close the connection when done 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Create a collection using the createCollection method const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents const docs = [ { name: "Alice", age: 25, address: "Wonderland" }, { name: "Bob", age: 30, address: "Builderland" }, { name: "Charlie", age: 35, address: "Chocolate Factory" } ]; //Insert multiple documents into the collection 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}`); }); //Specify conditions, update data based on the name parameter const filter = { name: "Alice" }; //Search criteria 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`); //Query the updated documents const updatedDocument = await collection.findOne(filter); console.log("Updated documents:"); console.log(updatedDocument); } finally { //Make sure to close the connection when done 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Create a collection using the createCollection method const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents const docs = [ { name: "Alice", age: 25, address: "Wonderland" }, { name: "Bob", age: 30, address: "Builderland" }, { name: "Alice", age: 28, address: "Old Wonderland" } ]; //Insert multiple documents into the collection 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}`); }); //Specify conditions, update multiple documents based on the name parameter const filter = { name: "Alice" }; //Search criteria 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`); //Query the updated documents const updatedDocuments = await collection.find(filter).toArray(); console.log("Updated documents:"); console.log(updatedDocuments); } finally { //Make sure to close the connection when done 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Create a collection using the createCollection method const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents const docs = [ { name: "Alice", age: 25, address: "Wonderland" }, { name: "Bob", age: 30, address: "Builderland" }, { name: "Charlie", age: 35, address: "Chocolate Factory" } ]; //Insert multiple documents into the collection 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}`); }); //Specify conditions, delete one document based on the name parameter const filter = { name: "Alice" }; //Search criteria const deleteResult = await collection.deleteOne(filter); console.log(`${deleteResult.deletedCount}document(s) have been deleted`); //Query all documents in the collection to confirm the deletion const remainingDocuments = await collection.find({}).toArray(); console.log("Remaining documents:"); console.log(remainingDocuments); } finally { //Make sure to close the connection when done 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Create a collection using the createCollection method const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents 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" } ]; //Insert multiple documents into the collection 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}`); }); //Specify conditions, delete multiple documents based on the name parameter const filter = { name: "Alice" }; //Search criteria const deleteResult = await collection.deleteMany(filter); console.log(`${deleteResult.deletedCount}document(s) have been deleted`); //Query all documents in the collection to confirm the deletion const remainingDocuments = await collection.find({}).toArray(); console.log("Remaining documents:"); console.log(remainingDocuments); } finally { //Make sure to close the connection when done 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Create a collection using the createCollection method const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents 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" } ]; //Insert multiple documents into the collection 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}`); }); //Sort the documents using the sort() method //Sort by the age field in ascending order const sortedDocsAsc = await collection.find().sort({ age: 1 }).toArray(); console.log("Documents sorted by the age field in ascending order:"); console.log(sortedDocsAsc); //Sort by the age field in descending order const sortedDocsDesc = await collection.find().sort({ age: -1 }).toArray(); console.log("Documents sorted by the age field in descending order:"); console.log(sortedDocsDesc); } finally { //Make sure to close the connection when done 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Create a collection using the createCollection method const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents 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" } ]; //Insert multiple documents into the collection 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}`); }); //Use the limit() method to limit the number of query results const limitedDocs = await collection.find().limit(3).toArray(); console.log("Limit the query results to 3 documents:"); console.log(limitedDocs); } finally { //Make sure to close the connection when done 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('example'); //Create a collection using the createCollection method const collectionName = 'exampleCollection'; await database.createCollection(collectionName); console.log(`collection ${collectionName}created successfully`); //Get the collection const collection = database.collection(collectionName); //Create multiple new documents 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" } ]; //Insert multiple documents into the collection 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}`); }); //Use the skip() method to skip the first two documents and return the remaining documents const skippedDocs = await collection.find().skip(2).toArray(); console.log("Query results after skipping the first two documents:"); console.log(skippedDocs); } finally { //Make sure to close the connection when done 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() { //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { //Connect to the MongoDB server await client.connect(); console.log("Successfully connected to the server"); //Specify the database const database = client.db('mydatabase'); //orders collection const ordersCollection = database.collection('orders'); //products collection const productsCollection = database.collection('products'); //Define the aggregation pipeline and use $lookup to perform a left outer join const pipeline = [ { $lookup: { from: 'products', //The name of the collection to join localField: 'product_id', //The field from the local collection to match foreignField: '_id', //The field from the joined collection to match as: 'productDetails' //The field name to include in the output results } } ]; //Execute the aggregation operation const result = await ordersCollection.aggregate(pipeline).toArray(); //Output the query results console.log("Left outer join query results:"); console.log(result); } finally { //Make sure to close the connection when finished 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"); //Delete the test collection dbo.collection("test").drop(function(err, delOK) { //If successful, delOK returns true; otherwise, it returns false 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'); //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); //Use Promise to wrap the process of connecting to the database function connectDB() { return new Promise((resolve, reject) => { //Connect to the MongoDB server client.connect((err) => { if (err) { reject(err); } else { console.log("Successfully connected to the MongoDB server"); resolve(client.db()); //Return the database instance } }); }); } //Usage example connectDB() .then(database => { //You can continue to perform database operations here console.log("Successfully connected to the database"); //Example: Output the name of the database console.log("Database name:", database.databaseName); //If you need to perform other operations, you can continue writing code here //For example, querying, inserting documents, etc. //Finally, close the connection 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'); //MongoDB connection URI const uri = "mongodb://localhost:27017"; //Please modify it according to your MongoDB server address //Create a new MongoClient const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); //Use Promise to wrap the process of connecting to the database function connectDB() { return new Promise((resolve, reject) => { //Connect to the MongoDB server client.connect((err) => { if (err) { reject(err); } else { console.log("Successfully connected to the MongoDB server"); resolve(client.db()); //Return the database instance } }); }); } //Function to add a document 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 to query documents 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 to update a document 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 to delete a document 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); } }); }); } //Usage example: Perform add, query, update, and delete operations sequentially async function performOperations() { try { const database = await connectDB(); //Add document const insertResult = await insertDocument(database, { name: "Document 1" }); //Query documents const findResult = await findDocuments(database); //Update document const updatedDocId = insertResult.insertedId; //Use the ID returned when inserting the document to update const updateResult = await updateDocument(database, updatedDocId, { name: "Updated Document 1" }); //Delete document const deleteResult = await deleteDocument(database, updatedDocId); //Output operation results console.log("Final operation completed:"); console.log("Delete document result:", deleteResult); } catch (err) { console.error("An error occurred while performing the operation:", err); } finally { //Make sure to close the connection when finished await client.close(); } } //Execute the operation performOperations();

Execution result:

数据库已连接
[ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ]
[ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ]
[]
Other extensions