📅  最后修改于: 2023-12-03 14:44:21.725000             🧑  作者: Mango
MongoDB JS InsertMany is a powerful function in JavaScript that allows you to insert multiple documents into a MongoDB collection at once. It saves you time and effort when you need to add a large amount of data to your database.
The syntax of MongoDB JS InsertMany function is:
db.collection.insertMany(
[ <document 1> , <document 2>, ..., <document N> ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
The insertMany()
function takes two parameters:
Here, the ordered flag specifies either the documents should be inserted in order or not. By default, it is set to true.
Consider the following example where we want to insert multiple documents to a users
collection.
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
const users = [
{ name: 'John', age: 25 },
{ name: 'Sarah', age: 28 },
{ name: 'Peter', age: 30 },
{ name: 'Paul', age: 35 }
];
db.collection("users").insertMany(users, function(err, res) {
if (err) throw err;
console.log(res.insertedCount + " documents inserted");
db.close();
});
});
In this example, we have created an array of four users, defined by their name and age. We then pass this array to the insertMany()
function using the db.collection
method. Finally, we log how many documents have been inserted and close the database connection.
In conclusion, MongoDB JS InsertMany is a handy function that can help you to insert multiple documents into a MongoDB collection at once. Its simple syntax and straightforward parameters make it easy to use, regardless of the size of your data set.