12

我有一个 Mongo 查找查询,可以很好地从大型文档中提取特定字段,例如...

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

...这会产生以下输出。请注意 SVersion 如何在文档中出现在 AVersion 之前,即使我的投影在 SVersion 之前要求 AVersion。

{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "3.5", "AVersion" : "4.0.3" } }
{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "4.0", "AVersion" : "4.0.3" } }

...问题是我希望输出是...

{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "3.5" } }
{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "4.0" } }

我需要做什么才能让 Mongo JavaScript shell 以我指定的字段顺序显示我的查询结果?

4

4 回答 4

8

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

{
_id : 0,      
"profile.ModelID" :"$profile.ModelID", 
"profile.AVersion":"$profile.AVersion",
"profile.SVersion":"$profile.SVersion"
}
于 2017-11-16T20:30:10.077 回答
7

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

简单的答案是你不能这样做。也许使用新的聚合框架是可能的。但这似乎只是为了订购字段。

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

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

最后一点,您不需要这样做,谁在乎字段返回的顺序。您的应用程序应该能够使用它需要的字段,而不管字段的顺序如何。

于 2012-08-16T00:54:23.963 回答
1

我应用的另一个解决方案如下:

db.profiles
  .find({ "profile.ModelID" : 'LZ241M4' })
  .toArray()
  .map(doc => ({
    profile: {
      ModelID: doc.profile.ModelID,
      AVersion: doc.profile.AVersion,
      SVersion: doc.profile.SVersion
    }
  }))
于 2020-09-16T14:18:55.553 回答
0

自 2.6 版(2014 年发布)以来,MongoDB 保留了写入操作( source)之后的文档字段的顺序。

PS 如果你使用 Python,你可能会觉得很有趣。

于 2019-03-22T08:07:55.187 回答