Sorting on Multiple fields mongo DB

前端 未结 3 435
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 15:50

I have a query in mongo such that I want to give preference to the first field and then the second field.

Say I have to query such that

db.col.find({         


        
相关标签:
3条回答
  • 2020-12-15 16:24

    That is true but there are two layers of ordering you have here since you are sorting on a compound index.

    As you noticed when the first field of the index matches the first field of sort it worked and the index was seen. However when working the other way around it does not.

    As such by your own obersvations the order needed to be preserved is query order of fields from first to last. The mongo analyser can sometimes move around fields to match an index but normally it will just try and match the first field, if it cannot it will skip it.

    0 讨论(0)
  • 2020-12-15 16:25

    The MongoDB query optimizer works by trying different plans to determine which approach works best for a given query. The winning plan for that query pattern is then cached for the next ~1,000 queries or until you do an explain().

    To understand which query plans were considered, you should use explain(1), eg:

    db.col.find({category:'A'}).sort({updated: -1}).explain(1)
    

    The allPlans detail will show all plans that were compared.

    If you run a query which is not very selective (for example, if many records match your criteria of {category: { $ne:'A'}}), it may be faster for MongoDB to find results using a BasicCursor (table scan) rather than matching against an index.

    The order of fields in the query generally does not make a difference for the index selection (there are a few exceptions with range queries). The order of fields in a sort does affect the index selection. If your sort() criteria does not match the index order, the result data has to be re-sorted after the index is used (you should see scanAndOrder:true in the explain output if this happens).

    It's also worth noting that MongoDB will only use one index per query (with the exception of $ors).

    So if you are trying to optimize the query:

    db.col.find({category:'A'}).sort({updated: -1, rating: -1})
    

    You will want to include all three fields in the index:

    db.col.ensureIndex({category: 1, updated: -1, rating: -1})
    

    FYI, if you want to force a particular query to use an index (generally not needed or recommended), there is a hint() option you can try.

    0 讨论(0)
  • 2020-12-15 16:36

    try this code it will sort data first based on name then keeping the 'name' in key holder it will sort 'filter'

     var cursor = db.collection('vc').find({   "name" :   { $in: [ /cpu/, /memo/ ]   }     }, { _id: 0, }).sort( { "name":1  ,  "filter": 1 } );
    
    0 讨论(0)
提交回复
热议问题