Reputation: 291
After aggregation I got this result. The _id field is each class's id and I applied {$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 },
... ]
The problem is _id value is not string type. so when I send JSON to client, it says malformed JSON.
How can I get string type _id? Thanks in advance.
Upvotes: 2
Views: 1607
Reputation: 9178
Don't form the JSON string yourself.
Use JSON.stringify( output_from_aggregation )
.
However, if you don't want do that, then do this.
"
), and not single quotes ('
). Strings in single quotes are invalid in JSON....
{ _id: 54c974bdff0d993b4ecf34ce, subject: 'science' }, score: 77.8712 },
...
...
{ _id: "54c974bdff0d993b4ecf34ce", subject: "science" }, score: 77.8712 },
...
More info:
Upvotes: 2
Reputation: 13753
In your case, _id is automatically generated and is of BSON (Binary JSON) type. You can manually choose _id as a String and write its value. For example
db.collection.insert( { _id: "10", item: "box", qty: 20 } )
you can see documentation for more detail on _id field http://docs.mongodb.org/manual/reference/method/db.collection.insert/
Upvotes: 1