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

前端 未结 4 1145
别那么骄傲
别那么骄傲 2020-12-03 15:09

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 performa

相关标签:
4条回答
  • 2020-12-03 15:52

    "While "$or"will always work, use "$in"whenever possible as the query optimizer handles it more efficiently."

    Moreover "$in" has more readability.

    Ref: MongoDB: The Definitive Guide

    0 讨论(0)
  • 2020-12-03 15:56

    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."

    0 讨论(0)
  • 2020-12-03 15:59

    Well that will insure no indecis to be ensured if you use $in, however i prefer to format it to $or as it will ensure index (readability won't concern me at is being handled in application logic in which i prefer to consume the memory of app rather than mongodb server)

    0 讨论(0)
  • 2020-12-03 16:03

    $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

    0 讨论(0)
提交回复
热议问题