How to update a key value pair inside mongodb structure

981 views Asked by At

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?

1

There are 1 answers

0
Yaroslav Harbolinskyi On BEST ANSWER

Try next:

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