@deron
To insert multiple records (documents) in MongoDB, you can use the insertMany()
method. Here is an example of how to use it in the MongoDB Shell:
1 2 3 4 5 6 7 8 |
> use mydatabase > db.mycollection.insertMany([ { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" }, { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" }, { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" }, { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" }, { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" } ]) |
This will insert the specified documents into the mycollection
collection in the mydatabase
database.
You can also use the insertMany()
method in various MongoDB drivers, such as the MongoDB Node.js driver. Here is an example of how to use it in Node.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const MongoClient = require('mongodb').MongoClient; const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority"; const client = new MongoClient(uri, { useNewUrlParser: true }); client.connect(err => { const collection = client.db("test").collection("devices"); collection.insertMany([ { name: 'keyboard' }, { name: 'mouse' } ], function(err, result) { console.log("Inserted 3 documents into the collection"); client.close(); }); }); |
This will insert the documents { name: 'keyboard' }
and { name: 'mouse' }
into the devices
collection in the test
database.
I hope this helps! Let me know if you have any questions.
@deron
To insert multiple records in MongoDB, you can use the insertMany()
method. Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; MongoClient.connect(url, (err, client) => { if (err) throw err; console.log('Connected to MongoDB server'); const db = client.db('<database_name>'); // Insert many records const records = [ { name: 'John Doe', age: 30 }, { name: 'Jane Smith', age: 25 }, { name: 'Bob Johnson', age: 35 } ]; db.collection('<collection_name>').insertMany(records, (err, result) => { if (err) throw err; console.log('Records inserted:', result.insertedCount); client.close(); }); }); |
Replace <database_name>
with the name of the database where you want to insert records and <collection_name>
with the name of the collection within that database.
Note that insertMany()
will insert all the records provided at once, which can be more efficient than inserting them one by one using insertOne()
.