- 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
MongoDB large collection and slow search? How to fix?
For faster search, create index. For this, use createIndex(). Let us create a collection with documents −
> db.demo661.createIndex({ListOfName:1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo661.insertOne({_id:1,ListOfName:["John","Robert","David"]}); { "acknowledged" : true, "insertedId" : 1 } > db.demo661.insertOne({_id:2,ListOfName:["Mike","Sam"]}); { "acknowledged" : true, "insertedId" : 2 } > db.demo661.insertOne({_id:3,ListOfName:["John","David","Bob"]}); { "acknowledged" : true, "insertedId" : 3 }
Display all documents from a collection with the help of find() method −
> db.demo661.find();
This will produce the following output −
{ "_id" : 1, "ListOfName" : [ "John", "Robert", "David" ] } { "_id" : 2, "ListOfName" : [ "Mike", "Sam" ] } { "_id" : 3, "ListOfName" : [ "John", "David", "Bob" ] }
Following is the query to fetch documents −
> db.demo661.find({"ListOfName": {"$all":["John","David"]}});
This will produce the following output −
{ "_id" : 1, "ListOfName" : [ "John", "Robert", "David" ] } { "_id" : 3, "ListOfName" : [ "John", "David", "Bob" ] }
Advertisements