Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Sort by field existing and then alphabetically

Tags:

mongodb

In my database I have a field of name. In some records it is an empty string, in others it has a name in it.

In my query, I'm currently doing:

db.users.find({}).sort({'name': 1})

However, this returns results with an empty name field first, then alphabetically returns results. As expected, doing .sort({'name': -1}) returns results with a name and then results with an empty string, but it's in reverse-alphabetical order.

Is there an elegant way to achieve this type of sorting?

like image 584
JVG Avatar asked Sep 20 '15 15:09

JVG


People also ask

How do I sort in MongoDB by alphabetical order?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Does MongoDB support sorting?

MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted.

How do I sort a case insensitive in MongoDB?

This means the only way to sort case insensitive currently is to actually create a specific "lower cased" field, copying the value (lower cased of course) of the sort field in question and sorting on that instead.

How do I sort a list in MongoDB by field?

MongoDB sort by field In MongoDB, for sorting the document by the field you have to use the sort () method. This method contains a list of fields. By using field names we can specify sorting in ascending and descending order by using 1 and -1 respectively.

Does MongoDB store documents in a particular order?

MongoDB does not store documents in a collection in a particular order. When sorting on a field which contains duplicate values, documents containing those values may be returned in any order. If consistent sort order is desired, include at least one field in your sort that contains unique values.

How do I get the ascending order of results in MongoDB?

In this example, I use the “make” text field to obtain the results in ascending order. The operator one ( {“make”:1}) is used to indicate the ascending order, and MongoDB projection is used to filter out all the other fields except the “make” field.

What is the Order of comparison in MongoDB?

This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field. When comparing values of different BSON types , MongoDB uses the following comparison order, from lowest to highest:


2 Answers

How about:

db.users.find({ "name": { "$exists": true } }).sort({'name': 1})

Because after all when a field you want to sort on is not actually present then the returned value is null and therefor "lower" in the order than any positive result. So it makes sense to exclude those results if you really are only looking for something with a matching value.

If you really want all the results in there and regarless of a null content, then I suggest you "weight" them via .aggregate():

db.users.aggregate([
     { "$project": {
         "name": 1,
         "score": {
             "$cond": [
                 { "$ifNull": [ "$name", false ] },
                 1,
                 10
             ]
         }
     }},
     { "$sort": { "score": 1, "name": 1 } }
])

And that moves all null results to the "end of the chain" by assigning a value as such.

like image 60
Blakes Seven Avatar answered Nov 30 '22 19:11

Blakes Seven


If you want to filter out documents with an empty "name" field, change your query: db.users.find({"name": {"$ne": ""}}).sort({"name": 1})

like image 21
Max Noel Avatar answered Nov 30 '22 21:11

Max Noel