Node.js
This page assume you have knowledge in Node.js.
info
Learn Node.js free and easy at LearnCodeNow.dev
Install
Install the official mongodb native driver for Node.js.
- npm
- Yarn
npm install mongodb --save
yarn add mongodb
Create database
/src/create-database.js
const { MongoClient } = require('mongodb');
// Replace the uri string with your connection string.
const uri = 'mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&w=majority';
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db('learndb');
const books = database.collection('books');
// Query for a book that has the title 'Learn MongoDB'
const query = { title: 'Learn MongoDB' };
const book = await books.findOne(query);
console.log(book);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Create collection
/src/create-collection.js
const mongodb = require('mongodb');
Run program
node .\index.js
Github
Download full source code at LearnCodeNow-dev/Learn-MongoDB