Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any build-in JSON.parse in MongoDB?

Is there any Mongo (command line) function that I can turn a string into object? e.g. JSON.parse or something like that?

db.sessions.update({}, {'$set':{ 'extra':JSON.parse(stringData) }});


my solution:

function my_extra() {
  db.tempData.find().forEach( function(obj) {
                       obj.extra = db.eval(obj.myString);
                       db.tempData.save(obj);
                     } );
};

my_extra();

However, I try this: db.tempData.update({}, {'$set':{ 'extra':db.eval(myString) }}); but it doesn't work.. saying myString is not defined. so i use this.myString but doesn't work neither. that's why I have to use the function.

is there a way to reference myString in the second parameter?

like image 268
murvinlai Avatar asked Oct 05 '11 19:10

murvinlai


2 Answers

The version 2.1+ Mongo shell includes a JSON utility object:

  • From object to JSON: JSON.serialize(object)
  • From JSON to object: JSON.parse(string)

http://api.mongodb.org/java/2.6/com/mongodb/util/JSON.html

Note: In version 2.4+ Mongo shell, use JSON.stringify() instead of JSON.serialize()
http://docs.mongodb.org/manual/release-notes/2.4-javascript/

like image 172
Alex Ross Avatar answered Oct 12 '22 12:10

Alex Ross


You can try eval function:

obj = eval("(function() { return {\"key\": \"value\"} })()")

But note it's unsafe because it can execute arbitrary Javascript code including db.dropDatabase().

like image 24
pingw33n Avatar answered Oct 12 '22 10:10

pingw33n