- 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
How do I query a MongoDB collection?
To query or return a MongoDB collection, use getCollection(). Let us create a collection with documents −
> db.demo294.insertOne({"EmployeeId":101,"EmployeeName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4d4a1a5d93261e4bc9ea36") } > db.demo294.insertOne({"EmployeeId":102,"EmployeeName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4d4a255d93261e4bc9ea37") } > db.demo294.insertOne({"EmployeeId":103,"EmployeeName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4d4a335d93261e4bc9ea38") }
Display all documents from a collection with the help of find() method −
> db.demo294.find();
This will produce the following output −
{ "_id" : ObjectId("5e4d4a1a5d93261e4bc9ea36"), "EmployeeId" : 101, "EmployeeName" : "Chris" } { "_id" : ObjectId("5e4d4a255d93261e4bc9ea37"), "EmployeeId" : 102, "EmployeeName" : "Bob" } { "_id" : ObjectId("5e4d4a335d93261e4bc9ea38"), "EmployeeId" : 103, "EmployeeName" : "David" }
Following is the query to get MongoDB collection −
> db.getCollection('demo294').find({ ... "EmployeeId":{$in:[101,103]}});
This will produce the following output −
{ "_id" : ObjectId("5e4d4a1a5d93261e4bc9ea36"), "EmployeeId" : 101, "EmployeeName" : "Chris" } { "_id" : ObjectId("5e4d4a335d93261e4bc9ea38"), "EmployeeId" : 103, "EmployeeName" : "David" }
Advertisements