Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering fields from find query with projection

Tags:

mongodb

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?

like image 963
Bob Kuhar Avatar asked Aug 15 '12 20:08

Bob Kuhar


People also ask

How do I print a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

Which field is always included in a projection unless specifically excluded?

The _id field is included automatically unless specifically excluded.


2 Answers

I have achieved it by projecting the fields using aliases, instead of including and excluding by 0 and 1s. Try this:

{
_id : 0,      
"profile.ModelID" :"$profile.ModelID", 
"profile.AVersion":"$profile.AVersion",
"profile.SVersion":"$profile.SVersion"
}
like image 172
Gulnur Avatar answered Nov 04 '22 03:11

Gulnur


Another solution I applied to achieve this is the following:

db.profiles
  .find({ "profile.ModelID" : 'LZ241M4' })
  .toArray()
  .map(doc => ({
    profile: {
      ModelID: doc.profile.ModelID,
      AVersion: doc.profile.AVersion,
      SVersion: doc.profile.SVersion
    }
  }))
like image 37
Adrien Joly Avatar answered Nov 04 '22 05:11

Adrien Joly