Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB v2.4.9 sort by boolean field

How do I sort query results based on a boolean field?

Consider the following collection:

{ "_id" : ObjectId("..."), "name" : "John" , "isFoo" : true}
{ "_id" : ObjectId("..."), "name" : "Jim" , "isFoo" : false}
{ "_id" : ObjectId("..."), "name" : "Joel" , "isFoo" : false}
{ "_id" : ObjectId("..."), "name" : "Jill" , "isFoo" : true}
{ "_id" : ObjectId("..."), "name" : "Samantha" , "isFoo" : true}

I need a query that will return the isFoo == true first and the isFoo == false documents second. In other words, I need to sort by a boolean field.

The following code is does not do the trick as I still get some documents with isFoo == true mixed in with the false ones.

db["users"].find().sort( { isFoo: 1 } )

Ideas?

like image 390
McMeep Avatar asked Apr 02 '14 13:04

McMeep


People also ask

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. The sort keys must be listed in the same order as defined in the index.

What is the use of sort () 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.

Does MongoDB have Boolean?

Boolean is a native field type in BSON (MongoDB's server-side storage format, aka "Binary JSON"). Booleans use less storage than an integer or string and avoid any unexpected side effects of comparison.


1 Answers

The code above works, my data was bad. As I wrote in the comment above, some of the documents had isFoo as a String (not Boolean) and that's why I was seeing the mixed results.

I had to change the type of the field from String to Boolean so I tried this:

db.users.find( { 'isFoo' : { $exists : true } } ).forEach( function (x) {   x.isFoo = new Boolean(x.isFoo);    db.users.save(x); });

But that just turned all of the isFoo fields to Objects.

Seeing as I was really tired of dealing with this issue I just used the following to set all the isFoo fields to false and just handle the changes manually.

db.users.find( { 'isFoo' : { $exists : true } } ).forEach( function (x) {   x.isFoo = false;    db.users.save(x); });

This was very annoying.

like image 54
McMeep Avatar answered Nov 15 '22 17:11

McMeep