2

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.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
monad98
  • 291
  • 4
  • 15
  • Do you need to include the `_id`? What are you doing with the `_id`? You could suppress it from the output. An ObjectId is an ObjectId - it's not a string or any type that can be directly represented in JSON and you'd need to decide on a strategy for representing it as a JSON type. – wdberkeley Jan 29 '15 at 06:27
  • You can use the toString() method to convert the _id to a string before sending it to the client. – joao Jan 29 '15 at 06:34

2 Answers2

2

Don't form the JSON string yourself. Use JSON.stringify( output_from_aggregation ).

However, if you don't want do that, then do this.

  • Make sure to form strings wrapped in double quotes ("), and not single quotes ('). Strings in single quotes are invalid in JSON.
  • You need to wrap the _id value in a string. It's an invalid hex number since it's too large to parse.

Old code:

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

New Code:

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

More info:

Community
  • 1
  • 1
Larry Battle
  • 9,008
  • 4
  • 41
  • 55
1

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/

Dev
  • 13,492
  • 19
  • 81
  • 174
  • yeah, I know. but the _id's are already ObjectId type and in my opinion changing them to string type is more challenging. – monad98 Jan 29 '15 at 06:29
  • You can use valueOf() method to find value of the ObjectId() object as a lowercase hexadecimal string. Example : ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() it's value is: 507c7f79bcf86cd7994f6c0e – Dev Jan 29 '15 at 06:58