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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With