我有一个Mongo查找查询,可以很好地从大文档中提取特定字段,如...
db.profiles.find(
{ "profile.ModelID" : 'LZ241M4' },
{
_id : 0,
"profile.ModelID" : 1,
"profile.AVersion" : 2,
"profile.SVersion" : 3
}
);
Run Code Online (Sandbox Code Playgroud)
...这会产生以下输出.请注意SVersion如何在文档中的AVersion之前出现,即使我的投影在SVersion之前要求AVersion.
{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "3.5", "AVersion" : "4.0.3" } }
{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "4.0", "AVersion" : "4.0.3" } }
Run Code Online (Sandbox Code Playgroud)
...问题是我想要输出...
{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "3.5" } }
{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "4.0" } }
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能让Mongo JavaScript shell以我指定的字段顺序显示查询结果?
我现在明白了.您希望返回按"字段"排序的结果,而不是字段的值.
简单的答案是你不能这样做.也许它可能与新的聚合框架.但这对于订购领域来说似乎有些过分.
查找查询中的第二个对象用于包含或排除返回的字段,而不是用于排序它们.
{
_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
}
Run Code Online (Sandbox Code Playgroud)
最后一点,您不需要这样做,谁关心字段重新出现的顺序.应用程序应该能够使用它需要的字段,而不管字段的顺序如何.
我通过使用别名投影字段来实现它,而不是通过 0 和 1 包括和排除。尝试这个:
{
_id : 0,
"profile.ModelID" :"$profile.ModelID",
"profile.AVersion":"$profile.AVersion",
"profile.SVersion":"$profile.SVersion"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5772 次 |
| 最近记录: |