- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements