@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.