YouTip LogoYouTip

Nodejs 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 operations on the database. If you don't have basic knowledge of MongoDB, you can refer to our tutorial: (#). ### Install Driver This tutorial uses [Taobao's customized cnpm command](#) for installation: $ cnpm install mongodb After successful installation, we can use the MongoClient object to connect to the database: ## Example const{ MongoClient }= require('mongodb'); async function(){ // 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 MongoDB server await client.connect(); console.log("Connected successfully to server"); }finally{ // Ensure the connection is closed after completion await client.close(); } } main().catch(console.error); After executing the above code, the output is: Connected successfully to server Connection parameter explanation: * `MongoClient`: This is the MongoDB client used to connect to the database. * `uri`: This is the MongoDB connection string, with the format `mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[?options]]`. * `useNewUrlParser` and `useUnifiedTopology` are options used to avoid some legacy connection behaviors. Next, we will implement CRUD (Create, Read, Update, Delete) operations. * * * ## 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 a 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("Connected successfully to server"); const database = client.db('tutorial'); const collection = database.collection('exampleCollection'); const doc = {name: "Example", type: "Test"}; const result = await collection.insertOne(doc); console.log(`New document created with ID: ${result.insertedId}`); }finally{await client.close(); }}main().catch(console.error); After executing the above code, the output is: Connected successfully to serverNew document created with 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("Connected successfully to server"); const database = client.db('tutorial'); 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 with ID: ${result.insertedId}`); }finally{await client.close(); }}main().catch(console.error); After executing the above code, the output is: Connected successfully to serverCollection exampleCollection created successfullyNew document created with ID: 6678e1b5c742b3ebd57f9759 * * * ## Database Operations (CRUD) Unlike MySQL, MongoDB automatically creates databases and collections, so we don't need to create them manually before use. ### Insert Data In the following example, we connect to the `exampleCollection` table in the `tutorial` database and insert one data record 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("Connected successfully to server"); const database = client.db('tutorial'); 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 with ID: ${result.insertedId}`); }finally{await client.close(); }}main().catch(console.error); Execute the following command, and the output is: Connected successfully to serverCollection exampleCollection created successfullyNew document created with ID: 6678e1d1f9503dc2e0e2a20b From the output, the data has been inserted successfully. We can also open the MongoDB client to view the data, like: > show dbs tutorial 0.000GB # Created the tutorial database> use tutorial # Switched to the tutorial database tutorial> show tables exampleCollection # Created the exampleCollection collection (table) # Automatically created the site collection (table) tutorial> db.exampleCollection.find()[ { _id: ObjectId('6678e1d1f9503dc2e0e2a20b'), name: 'Alice', age: 25, address: 'Wonderland' }] To insert multiple documents, you can use `insertMany()`: ## 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("Connected successfully to server"); const database = client.db('tutorial'); 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 with IDs:`); Object.keys(result.insertedIds).forEach((key, index) =>{console.log(`Document ${index + 1}: ${result.insertedIds}`); }); }finally{await client.close(); }}main().catch(console.error); The output is: Connected successfully to serverCollection exampleCollection created successfully3 new documents created with IDs:Document 1: 6678e30e80ac30e5e689f13aDocument 2: 6678e30e80ac30e5e689f13bDocument 3: 6678e30e80ac30e5e689f13c ### Query Data You can use `find()` to retrieve data. `find()` returns all data matching the specified criteria. If no criteria 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("Connected successfully to server"); const database = client.db('tutorial'); 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 with IDs:`); 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 output is: Connected successfully to serverCollection exampleCollection created successfully3 new documents created with IDs:Document 1: 0Document 2: 1Document 3: 2Queried documents:[ { name: 'Alice', age: 25, address: 'Wonderland' }, { name: 'Bob', age: 30, address: 'Builderland' }, { name: 'Charlie', age: 35, address: 'Chocolate Factory' }] The following example retrieves the instance where the name is "Alice": ## Query Data with Specific 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("Connected successfully to server"); const database = client.db('tutorial'); 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 with IDs:`); 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); Execute the following command, and the output is: Connected successfully to serverCollection exampleCollection created successfully3 new documents created with IDs:Document 1: 0Document 2: 1Document 3: 2Queried documents:[ { name: 'Alice', age: 25, address: 'Wonderland' }] ### Update Data We can also modify data in the database. The following example updates the data where the 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("Connected successfully to server"); const database = client.db('tutorial'); 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 with IDs:`); 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) was/were updated`); const updatedDocument = await collection.findOne(filter); console.log("Updated document:"); console.log(updatedDocument); }finally{await client.close(); }}main().catch(console.error); After successful execution, the output is as follows: Connected successfully to serverCollection exampleCollection created successfully3 new documents created with IDs:Document 1: 0Document 2: 1Document 3: 21 document(s) matched the filter criteria1 document(s) was/were updatedUpdated document:{ _id: new ObjectId('6678e1d1f9503dc2e0e2a20b'), name: 'Alice', age: 28, address: 'New Wonderland'} To update all documents that match the criteria, you can use `updateMany()`: ## 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("Connected successfully to server"); const database = client.db('tutorial'); 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 documents created with IDs:`); 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) was/were 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 the 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("Connected successfully to server"); const database = client.db('tutorial'); 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 with IDs:`); 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) was/were deleted`); const remainingDocuments = await collection.fi
← Jsref CopywithinNodejs Mysql β†’