How are null values in a MongoDB index sorted?

前端 未结 2 1125
情话喂你
情话喂你 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条回答
  •  萌比男神i
    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 } );
    

提交回复
热议问题