Ordering fields from find query with projection

mongodb

Solution

I get it now. You want to return results ordered by "fields" rather the value of a fields.

Simple answer is that you can't do this. Maybe its possible with the new aggregation framework. But this seems overkill just to order fields.

The second object in a find query is for including or excluding returned fields not for ordering them.

  {
    _id : 0,               // 0 means exclude this field from results
    "profile.ModelID" : 1, // 1 means include this field in the results
    "profile.AVersion" :2, // 2 means nothing
    "profile.SVersion" :3, // 3 means nothing
  }

Last point, you shouldn't need to do this, who cares what order the fields come-back in. You application should be able to make use of the fields it needs regardless of the order the fields are in.

Problem

I have a Mongo find query that works well to extract specific fields from a large document like... ``` db.profiles.find( { "profile.ModelID" : 'LZ241M4' }, { _id : 0, "profile.ModelID" : 1, "profile.AVersion" : 2, "profile.SVersion" : 3 } ); ``` ...this produces the following output. Note how the SVersion comes before the AVersion in the document even though my projection asked for AVersion before SVersion. ``` { "profile" : { "ModelID" : "LZ241M4", "SVersion" : "3.5", "AVersion" : "4.0.3" } } { "profile" : { "ModelID" : "LZ241M4", "SVersion" : "4.0", "AVersion" : "4.0.3" } } ``` ...the problem is that I want the output to be... ``` { "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "3.5" } } { "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "4.0" } } ``` What do I have to do get the Mongo JavaScript shell to present the results of my query in the field order that I specify?

Original source

Related problems