Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a dollar sign (.$.) in a JSON key do?

Tags:

mongodb

I was trying to change the strength based on the hero name in a document like this:

"_id" : ObjectId("52b0d27b5dee463864000001"),
"author" : "niko",
"permalink" : "super_heroes" 
"hero" : [
    {
        "name" : "Batman",
        "strength" : 1,
        "magic" : [ ],
        "times" : [ ]
    },

I couldn't change it when initially trying:

var operator = { '$set' : { 'hero.strength' : strength } }; 

var query = { 'permalink': permalink , 'hero.name':name };
posts.update(query, operator, options, function(err, numModified) {...})

I got MongoError: can't append to array using string field name: strength.

But after seeing this post I added a dollar sign and it worked:

var operator = { '$set' : { 'hero.$.strength' : strength } }; 

What did that dollar sign in a JSON key do? I tried googling it, but I just came up with a million explanations of what jQuery is. Thank you.

like image 326
Squirrl Avatar asked Dec 17 '13 23:12

Squirrl


1 Answers

This is not a JSON operator (there is no such things as JSON operator. You might think that JSON is a string).

In this context $ is a mongodb positional operator to perform update in a specific position.

like image 189
Salvador Dali Avatar answered Nov 15 '22 04:11

Salvador Dali