Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimized way of Querying in MongoDB using $in vs $or

Tags:

mongodb

Implementing an application that looks up a table for mail id presence from a list of around 10 email ids. Tried using $or and $in.

$in seems to give better performance but not significant. Is one more optimized than other?

like image 851
Amareswar Avatar asked Feb 06 '13 18:02

Amareswar


People also ask

Can we run query efficiently in MongoDB?

Performance. Because the index contains all fields required by the query, MongoDB can both match the query conditions and return the results using only the index. Querying only the index can be much faster than querying documents outside of the index.

What method can we use to maximize performance and prevent MongoDB from returning more results than required for processing?

You must apply limit() to the cursor before retrieving any documents from the database. Use limit() to maximize performance and prevent MongoDB from returning more results than required for processing.

What are some tips to improve the performance of NoSQL queries?

Add Appropriate Indexes NoSQL databases require indexes, just like their relational cousins. An index is built from a set of one or more fields to make querying fast.


2 Answers

MongoDB docs have the answer:

"When using $or with <expressions> that are equality checks for the value of the same field, choose the $in operator over the $or operator."

like image 162
Asya Kamsky Avatar answered Oct 28 '22 10:10

Asya Kamsky


$or operator is logical operator where you can define your own login but $in operator is Comparison operator where you can compare you can not put your on logic.

Syntax of $in:

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

Example:

db.account.find( { qty: { $in: [ 5, 15 ] } } )

Syntax of $or:

{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

Example:

db.account.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )

Note: Account is your collection name

like image 21
Aamod Tiwari Avatar answered Oct 28 '22 09:10

Aamod Tiwari