8

I am doing something wrong or I don't understand $push (probably don't understand). Anyway I have the following document:

{
  "_id" : ObjectId("501c83051d41c8753e000000"), 
  "node" : "denver", 
  "enc" : {
    "environment" : "production",
    "classes" : {
      "denver" : ""
    }
  }, 
  "inherit" : "default"
}

And I am trying to make the document

{
  "_id" : ObjectId("501c83051d41c8753e000000"), 
  "node" : "denver", 
  "enc" : {
    "environment" : "production", 
    "classes" : {
      "denver" : "",
      "boulder" : ""
    }
  }, 
  "inherit" : "default"
}

This is what my update statement looks like:

col.update(
  {
    'node' : 'denver'
  }, 
  {
    '$push': {
      'enc.classes' : {
        'boulder': ''
      }
    }
  },
True)

I don't get an error but the document never updates. If I change $push to $set then the denver is replaced with boulder.

Thanks for any assistance.

Nalum
  • 4,143
  • 5
  • 38
  • 55
Brian Carpio
  • 493
  • 3
  • 9
  • 15

2 Answers2

15

$push does not work in this case because you are trying to use an array function on an object.

To use $push you would need to change your data structure to the following:

{
    "_id" : ObjectId("501c83051d41c8753e000000"), 
    "node" : "denver", 
    "enc" : {
        "environment" : "production", 
        "classes" : [
            "denver"
        ]
    }, 
    "inherit" : "default"
}

Then your query would be:

col.update(
    {
        'node' : 'denver'
    },
    {
        '$push': {
            'enc.classes' : 'boulder'
        }
    },
    True
)
Nalum
  • 4,143
  • 5
  • 38
  • 55
10

This query works.

db.foo.update({"node": "denver"}, {"$set": {"enc.classes.boulder": ""}}
j0k
  • 22,600
  • 28
  • 79
  • 90
Lujeni
  • 356
  • 2
  • 10
  • 1
    It is most excellent to see Boulder used in accepted answers. – kkurian Jan 31 '13 at 22:33
  • 3
    In PyMongo 3.x 'update' has been depreciated. You can do the same thing and $push to an array using the following: db.foo.update_one({"node": "denver"}, {"$push": {"enc.classes.boulder": ""}} – Lionel Morrison Jan 26 '16 at 21:05