lec_7_part_2
lec_7_part_2
mongodb driver
install the mongodb driver module from the NPM repository, so that a Node.js
application could interact with MongoDB:
npm install mongodb
Output:
Database created
MongoDatabase { s: { client: [MongoClient], options: [Object], dbName:
'mydatabase' } }
4
Output:
Collection created
Collection { s: { db: [MongoDatabase], options: [Object], name: 'products' } }
5
InsertOne() method
Example
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);
insertMany()
Example
const {MongoClient} = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
//const uri = "mongodb+srv://user:[email protected] db.net / ?
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
},
{
7
'ProductID': 5,
'Name': 'Printer',
'price': 9000
}
]);
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);
Output:
5 new document(s) created with the following id(s):
{
'0': <ObjectId>,
'1': <ObjectId>,
'2': <ObjectId>,
'3': <ObjectId>,
'4': <ObjectId>
}