How are null values in a MongoDB index sorted?

前端 未结 2 1049
情话喂你
情话喂你 2021-01-17 16:55

I want to sort my index in a specific way (-1, 1) and want to make sure that null values are at the top of the index. How can I ensure this?

相关标签:
2条回答
  • 2021-01-17 17:38

    You have said" I just want to basically have an 'if one with null exists take it, else take one without' by one query", how about db.collection.find().sort().limit(1) ?

    0 讨论(0)
  • 2021-01-17 17:41

    If you are sorting descending and you are seeing null values at the end, that would be the default behaviour of the sort.

    There's really not much that can be done to change that behaviour, but a workaround that will give you the results you're looking for is to do two queries instead of one:

    db.Collection.find( { a: null } );
    db.Collection.find( { a: { $ne: null } } ).sort( { a: -1, b: 1 } );
    
    0 讨论(0)
提交回复
热议问题