带投影的查找查询中的排序字段 [英] Ordering fields from find query with projection
问题描述
我有一个Mongo查找查询,可以很好地从大型文档中提取特定字段,例如...
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
}
);
...这将产生以下输出.请注意,即使我的投影要求在SVersion之前要求AVersion,SVersion还是比文档中的AVersion早.
...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" } }
我该怎么做才能使Mongo JavaScript Shell以我指定的字段顺序显示查询结果?
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?
推荐答案
我现在明白了.您想返回按字段"排序的结果,而不是字段的值.
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.
这篇关于带投影的查找查询中的排序字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!