Search code examples
mongodbmongodb-update

How to update a key value pair inside mongodb structure


I have a mongodb collection where objects are structured as such:

{
  "id": "1234",
  "history": [
    {
      "userid": 100,
      "myobjects": [{id, id1, id4}]
    },
    {
      "userid": 200,
      "myobjects": [{id2, id3, id5}]
    },
}

I'm trying to add an entry to the users array, with the following javascript:

Collection.update(
  { "_id" : 1234 },
    { $push: 
      { 
        "history.userid" : 300, 
        "history.$.myobjects" : object_var 
      }
  }
);

I'm getting a "can't set field named $" error. Any ideas how I can push to this sub-object?


Solution

  • Try next:

    Collection.update(
    { "_id" : 1234 },
    {
        $push: {
            history: {
                "userid" : 300,
                "myobjects" : [{id2, id3, id5}]
            }
        }
    }
    );