Steps to insert documents into a collection using Node.js and the MongoDB driver:
1. Install MongoDB Driver:
Use npm to install the official MongoDB Node.js driver:
npm install mongodb
2. Connect to MongoDB:
Create a Node.js file (e.g., insert_data.js) and establish a connection to your MongoDB instance using MongoClient:
const { MongoClient } = require('mongodb');
const uri = "mongodb://your_connection_string"; // Replace with your actual connection string
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect((err) => {
if (err) {
console.error(err);
return;
}
console.log("Connected to MongoDB!");
// Proceed with inserting data after successful connection
// Close the connection after operations (shown later)
});
3. Insert a Single Document:
Once connected, you can use the insertOne() method to insert a single document into your collection:
const db = client.db("your_database_name"); // Replace with your database name
const collection = db.collection("your_collection_name"); // Replace with your collection name
const dataToInsert = { name: "John Doe", age: 30 }; // Replace with your data
collection.insertOne(dataToInsert, (err, result) => {
if (err) {
console.error(err);
return;
}
console.log("Document inserted successfully!");
console.log("Inserted ID:", result.insertedId); // Get the generated _id
// Close the connection here
client.close();
});
Explanation:
-
We obtain database and collection objects using
client.db()anddb.collection(). -
We define the data (
dataToInsert) as a JavaScript object containing the fields and values you want to store in the document. -
The
insertOne()method takes the data object and a callback function as arguments. -
The callback function handles potential errors (
err) and the result (result). -
If successful, the result object contains the
insertedId, which is the unique identifier assigned by MongoDB to the inserted document. -
Finally, we close the connection using
client.close().
4. Insert Multiple Documents:
To insert multiple documents at once, you can use the insertMany() method:
const dataToInsert = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 40 },
{ name: "Charlie", age: 35 },
];
collection.insertMany(dataToInsert, (err, result) => {
if (err) {
console.error(err);
return;
}
console.log("Documents inserted successfully!");
console.log("Inserted IDs:", result.insertedIds); // Array of generated IDs
// Close the connection here
client.close();
});
Explanation:
-
We define
dataToInsertas an array of JavaScript objects, each representing a document. -
The
insertMany()method takes the array of data objects and a callback function. -
The callback function handles errors and the result (
result). -
If successful, the
resultobject contains aninsertedIdsproperty, which is an array containing the unique identifiers for each inserted document.
Remember:
-
Replace placeholders like
"your_connection_string","your_database_name", and"your_collection_name"with your actual credentials. -
Close the connection after your operations are complete.
-
These examples demonstrate basic usage. The MongoDB driver offers additional methods for more complex insert operations.