使用投影查找查询中的字段

Bob*_*har 7 mongodb

我有一个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以我指定的字段顺序显示查询结果?

jam*_*jam 8

我现在明白了.您希望返回按"字段"排序的结果,而不是字段的值.

简单的答案是你不能这样做.也许它可能与新的聚合框架.但这对于订购领域来说似乎有些过分.

查找查询中的第二个对象用于包含或排除返回的字段,而不是用于排序它们.

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

最后一点,您不需要这样做,谁关心字段重新出现的顺序.应用程序应该能够使用它需要的字段,而不管字段的顺序如何.

  • 从实际的角度来看,纯粹作为个人偏好,在开发或调试期间使用mongodb shell时能够对输出字段进行排序会很有帮助.当我执行`find()`时,我不总是*想要将`_id`字段看作第一个输出列.是的,我*可能*希望看到`_id`,但我首先对其他领域更感兴趣,所以*总是*首先看到`_id`,当它包含在内时可以被认为是噪音. (6认同)
  • 我并不认为你的"过度杀戮"是按照投影建议的顺序返回的字段,但它的mongo; 我已经习惯了失望.谢谢你的帮助. (2认同)
  • @GatesVP:字段顺序相关的一个明显用例是在mongo shell中显示`find()`的结果.我已经为此提交了一张票 - https://jira.mongodb.org/browse/SERVER-12599 (2认同)

Gul*_*nur 7

我通过使用别名投影字段来实现它,而不是通过 0 和 1 包括和排除。尝试这个:

{
_id : 0,      
"profile.ModelID" :"$profile.ModelID", 
"profile.AVersion":"$profile.AVersion",
"profile.SVersion":"$profile.SVersion"
}
Run Code Online (Sandbox Code Playgroud)