mongodb 聚合:按 _id 分组

mongodb aggregation: group by _id

汇总后我得到了这个结果。 _id 字段是每个 class 的 ID,我应用了 {$group:{_id:"$_id", .....

[{ _id: 54c977314f5293b74ea54f96, subject: 'math' }, score: 73.5335 },
{ _id: 54c977314f5293b74ea54f96, subject: 'science' }, score: 56.2192 },
{ _id: 54c977314f5293b74ea54f96, subject: 'history' }, score: 82.8821 },
{ _id: 54c974bdff0d993b4ecf34ce, subject: 'math' }, score: 68.2598 },
{ _id: 54c974bdff0d993b4ecf34ce, subject: 'science' }, score: 77.8712 },
{ _id: 54c974bdff0d993b4ecf34ce, subject: 'history' }, score: 71.9218 },
                                 ...                                  ]

问题是_id 值不是字符串类型。所以当我发送 JSON 给客户时,它说 JSON.

格式错误

如何获取字符串类型_id?提前致谢。

在你的例子中,_id 是自动生成的,并且是 BSON (Binary JSON) 类型。 您可以手动选择 _id 作为字符串并写入其值。例如

db.collection.insert( { _id: "10", item: "box", qty: 20 } )

您可以查看有关 _id 字段的更多详细信息的文档 http://docs.mongodb.org/manual/reference/method/db.collection.insert/

不要自己组成 JSON 字符串。 使用 JSON.stringify( output_from_aggregation ).

但是,如果您不想那样做,那么就这样做。

  • 确保形成用双引号 (") 包裹的字符串,而不是单引号 (')。单引号中的字符串在 JSON.
  • 中无效
  • 您需要将 _id 值包装在一个字符串中。这是一个无效的十六进制数,因为它太大而无法解析。

旧代码:

...
{ _id: 54c974bdff0d993b4ecf34ce, subject: 'science' }, score: 77.8712 },
...

新代码:

...
{ _id: "54c974bdff0d993b4ecf34ce", subject: "science" }, score: 77.8712 },
...

更多信息: