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(o开发者_Python百科bj);
} );
};
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?
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/
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()
.
精彩评论