Selecting database inside the JS in MongoDB?


You can use getSiblingDB() from MongoDB for this using var keyword from JS −

anyVariableName= db.getSiblingDB(‘yourDatabaseName’);

Let us implement the above syntax in order to select database −

> selectedDatabase = db.getSiblingDB('sample');

This will produce the following output −

Sample

Now, insert some documents. Let’s say the collection is ‘selectDatabaseDemo’ −

> db.selectDatabaseDemo.insertOne({"ClientName":"John Smith","ClientAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda794b5667f1cce01d55ad")
}
> db.selectDatabaseDemo.insertOne({"ClientName":"Carol Taylor","ClientAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda79565667f1cce01d55ae")
}

Display all documents from a collection with the help of find() method −

db.selectDatabaseDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cda794b5667f1cce01d55ad"),
   "ClientName" : "John Smith",
   "ClientAge" : 23
}
{
   "_id" : ObjectId("5cda79565667f1cce01d55ae"),
   "ClientName" : "Carol Taylor",
   "ClientAge" : 24
}

Updated on: 30-Jul-2019

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements