”;
MongoDB is a document-oriented database, which can be interfaced with Node.js through the NPM module called mongodb. A Document is the heart of a MongoDB database. It is a collection of key-value pairs. We can also think of it being similar to single row in a table of SQL based relational database, just as a Collection in MongoDB is analogous to a table in relational database. The NPM mongodb package provides insertOne() and insertMany() methods, using which one or more Documents can be added into a Collection, from within a Node.js application.
MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents. MongoDB documents are composed of field-and-value pairs and have the following structure −
{ field1: value1, field2: value2, field3: value3, ... fieldN: valueN }
The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents.
Each document is characterised by a special key called “_id” having a unique value, similar to primary key in entity table of a relational database. A key is also referred to as a field. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.
insertOne() method
The Collection object has insertOne() method that inserts a single document into the collection.
Collection.insertOne(doc)
The document to insert is passed as an argument. It inserts a single document into MongoDB. If documents passed in do not contain the _id field, one will be added to each of the documents missing it by the driver, mutating the document.
Example
With the following code, we insert a single document into the products collection in the database.
const {MongoClient} = require(''mongodb''); async function main(){ const uri = "mongodb://localhost:27017"; const client = new MongoClient(uri); try { // Connect to the MongoDB cluster await client.connect(); // Make the appropriate DB calls // Create a single new document await createdoc(client, "mydatabase", "products", { "ProductID":1, "Name":"Laptop", "Price":25000 }); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function createdoc(client, dbname, colname, doc){ const dbobj = await client.db(dbname); const col = dbobj.collection(colname); const result = await col.insertOne(doc); console.log(`New document created with the following id: ${result.insertedId}`); }
Output
New listing created with the following id: 65809214693bd4622484dce3
The Mongo shell can also be used to view the document inserted.
> use mydb; < switched to db mydb > products=db[''products''] < mydb.products > docs=products.find() { _id: ObjectId("65809214693bd4622484dce3"), ProductID: 1, Name: ''Laptop'', Price: 25000 }
insertMany() method
The insertMany() method of the Collection object makes it possible to insert more than one documents. An array of JSON documents is used as the argument. We also use SRV connection string the following example −
Example
const {MongoClient} = require(''mongodb''); async function main(){ //const uri = "mongodb://localhost:27017"; const uri = "mongodb+srv://user:[email protected]/?retryWrites=true&w=majority"; const client = new MongoClient(uri); try { // Connect to the MongoDB cluster await client.connect(); // Make the appropriate DB calls // insert documents await createdocs(client, [ {''ProductID'':1, ''Name'':''Laptop'', ''price'':25000}, {''ProductID'':2, ''Name'':''TV'', ''price'':40000}, {''ProductID'':3, ''Name'':''Router'', ''price'':2000}, {''ProductID'':4, ''Name'':''Scanner'', ''price'':5000}, {''ProductID'':5, ''Name'':''Printer'', ''price'':9000} ]); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function createdocs(client, docs){ const result = await client.db("mydb").collection("products").insertMany(docs); console.log(`${result.insertedCount} new document(s) created with the following id(s):`); console.log(result.insertedIds); }
Output
5 new listing(s) created with the following id(s): { ''0'': new ObjectId(''6580964f20f979d2e9a72ae7''), ''1'': new ObjectId(''6580964f20f979d2e9a72ae8''), ''2'': new ObjectId(''6580964f20f979d2e9a72ae9''), ''3'': new ObjectId(''6580964f20f979d2e9a72aea''), ''4'': new ObjectId(''6580964f20f979d2e9a72aeb'') }
You can export the collection of document in CSV format.
_id,ProductID,Name,Price,price 65809214693bd4622484dce3,1,Laptop,25000, 6580964f20f979d2e9a72ae8,2,TV,40000 6580964f20f979d2e9a72ae9,3,Router,2000 6580964f20f979d2e9a72aea,4,Scanner,5000 6580964f20f979d2e9a72aeb,5,Printer,9000
”;