📜  mongodb insert (1)

📅  最后修改于: 2023-12-03 15:32:56.556000             🧑  作者: Mango

MongoDB Insert

MongoDB is a popular NoSQL document-oriented database that provides scalability, high performance, and flexibility in data modeling. In this tutorial, we will learn how to insert data into MongoDB using the insert method.

Prerequisites

Before we proceed, make sure you have MongoDB installed on your system. You can download and install MongoDB from the official website. Also, ensure you have a basic understanding of MongoDB data modeling and the CRUD (Create, Read, Update, Delete) operations.

Connecting to the Database

To connect to the MongoDB database server, we need to have the mongodb driver installed. You can install the driver using the following command:

npm install mongodb

To connect to the database, we need to provide a connection string as follows:

const { MongoClient } = require('mongodb');

// Replace the URL with your MongoDB deployment's connection string.
const uri = 'mongodb+srv://<username>:<password>@<clusterName>.mongodb.net/';

const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    console.log('Connected to the database');
  } catch (err) {
    console.error(err);
  }
}

run().catch(console.error);

Make sure to replace the <username>, <password>, and <clusterName> placeholders with the values from your MongoDB deployment.

Inserting Data

To insert data into MongoDB, we use the insertOne method, which inserts a single document into a collection. The method takes an object as a parameter, which represents the document to be inserted.

const db = client.db('<dbname>');

const collection = db.collection('<collection-name>');

const document = { name: 'John Doe', email: 'johndoe@example.com' };

const result = await collection.insertOne(document);

console.log(`${result.insertedCount} documents were inserted`);

In the above example, we first get a reference to the database and the collection we want to insert into using the db and collection methods of the MongoClient object, respectively.

We then create a document as an object with two fields, name and email, and insert it into the collection using the insertOne method. The method returns a WriteResult object, which contains information about the insertion operation, such as the number of documents inserted.

Bulk Insert

In some scenarios, we might want to insert multiple documents into a collection at once. MongoDB provides the insertMany method for this purpose. The method takes an array of documents as a parameter and inserts them into the collection.

const documents = [
  { name: 'Jane Doe', email: 'janedoe@example.com' },
  { name: 'Bob Smith', email: 'bobsmith@example.com' },
  { name: 'Alice Brown', email: 'alicebrown@example.com' },
];

const result = await collection.insertMany(documents);

console.log(`${result.insertedCount} documents were inserted`);

In the above example, we create an array of documents and insert them into the collection using the insertMany method.

Conclusion

In this tutorial, we learned how to insert data into MongoDB using the insertOne and insertMany methods. We also saw how to connect to the MongoDB database and get a reference to a collection. Now that you know how to insert data into MongoDB, you can start building your own applications using this powerful database.