Monday, 8 November 2021

MongoDB

Install MongoDB in Ubuntu.

start stop server

1. start
sudo systemctl start mongod

2. check status
sudo systemctl status mongod

3. stop
 sudo systemctl stop mongod

4. restart
sudo systemctl restart mongod

5. use mongosh
mongosh

Find connect uri

mongosh

//should see something like the below
Connecting to:mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000

Use node.js to connect to MongoDB

Install node.js MongoDB driver

npm install mongodb --save

Connect

//put it in index.js
const { MongoClient } = require("mongodb");

// Connection URI
const uri = "mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000";

// Create a new MongoClient
const client = new MongoClient(uri);

//database name
const dbName = 'leo_test_db';

async function run() {
  try {
    // Connect the client to the server
    await client.connect();

    // Establish and verify connection
    await client.db("admin").command({ ping: 1 });
    console.log("Connected successfully to server");
    
    const db = client.db(dbName);
    const collection = db.collection('books');

    const insertResult = await collection.insertMany([{'java':2005}, {'PHP':2010}]);
    console.log("insert result", insertResult)

    } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

//run it
node index.js

//output Connected successfully to server

Basic CRUD operations

//insert one
const insertResult = await collection.insertOne({'go':2021});

//insert multiple items
const insertResult = await collection.insertMany([{'java':2005}, {'PHP':2010}]);

mongo shell reference

//open shell
mongosh
//show databases
show dbs

Create a new database

mongosh

//want to create db called newswatcherdb. This command will work
//even we do not have this db yet
use newswatcherdb

//need to add something into db to create db
db.user.insert({name:"leo"})

//new created db in the list
show dbs

//show collections in db
use leo_test_db
show collections //get books
db.books.find() // will show items in collection

Some useful links

No comments:

Post a Comment