
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
In MongoDB, is using $in search faster than multiple single searches?
Yes, using $in is faster. Let us see an example and create a collection with documents −
> db.demo653.insertOne({subject:"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04b274deddd72997713c0") } > db.demo653.insertOne({subject:"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04b304deddd72997713c1") } > db.demo653.insertOne({subject:"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04b354deddd72997713c2") } > db.demo653.insertOne({subject:"C"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04b384deddd72997713c3") } > db.demo653.insertOne({subject:"C++"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04b3b4deddd72997713c4") }
Display all documents from a collection with the help of find() method −
> db.demo653.find();
This will produce the following output −
{ "_id" : ObjectId("5ea04b274deddd72997713c0"), "subject" : "MySQL" } { "_id" : ObjectId("5ea04b304deddd72997713c1"), "subject" : "MongoDB" } { "_id" : ObjectId("5ea04b354deddd72997713c2"), "subject" : "Java" } { "_id" : ObjectId("5ea04b384deddd72997713c3"), "subject" : "C" } { "_id" : ObjectId("5ea04b3b4deddd72997713c4"), "subject" : "C++" }
Following is the query to use $in and search faster than multiple single searches −
> db.demo653.find({subject:{$in:["MySQL","C++","C"]}});
This will produce the following output −
{ "_id" : ObjectId("5ea04b274deddd72997713c0"), "subject" : "MySQL" } { "_id" : ObjectId("5ea04b384deddd72997713c3"), "subject" : "C" } { "_id" : ObjectId("5ea04b3b4deddd72997713c4"), "subject" : "C++" }
Advertisements