Order fields from a search query with projection

I have a Mongo search query that works well to extract certain fields from a large document, for example ...

db.profiles.find( { "profile.ModelID" : 'LZ241M4' }, { _id : 0, "profile.ModelID" : 1, "profile.AVersion" : 2, "profile.SVersion" : 3 } ); 

... this produces the following conclusion. Note that SVersion appears before AVersion in the document, although my projection asked 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 result 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 need to do so that the Mongo JavaScript shell presents the results of my query in the field order that I specify?

+6
source share
2 answers

I get it now. You want to return results ordered by "fields" and not by field value.

The simple answer is: you cannot do this. Perhaps this is possible with a new aggregation structure. But it seems redundant to streamline the fields.

The second object in the search query is the inclusion or exclusion of the returned fields, not their ordering.

  { _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 } 

In the latter case, you do not need to do this, who cares about in what order the fields are returned. Your application should be able to use the fields it needs, regardless of the order in which the fields are.

+7
source

I achieved this by projecting fields using aliases instead of including and excluding 0 and 1. Try the following:

 { _id : 0, "profile.ModelID" :"$profile.ModelID", "profile.AVersion":"$profile.AVersion", "profile.SVersion":"$profile.SVersion" } 
0
source

Source: https://habr.com/ru/post/922984/


All Articles