7

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.

Burt_Harris
  • 6,415
  • 2
  • 29
  • 64
Squirrl
  • 4,909
  • 9
  • 47
  • 85

1 Answers1

9

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.

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753