0

I am using mongodb update method with upsert=true.

My data looks like this:

{"my_id":"1",
"test_list":[{"test_id":1,"test_name":"pppp"}]}

now I am using the following command:

db.testcol.update({"my_id":1,"test_list.test_id":2},{"$set":{"test_list.$.test_name":"mmmm"}},true,true)

Now I want a new object inserted into the "test_list" as it does not exist

but I am getting the error:

Cannot apply the positional operator without a corresponding query field containing an array.

I cannot use "insert" for my operation, as I dont know whether the data is their and the field needs to be updated,or its not their and needs to be inserted(for the first time)

Phalguni Mukherjee
  • 623
  • 3
  • 11
  • 29

1 Answers1

0

Upserts are for when you want the update to work whether the entire document is there or not, not just an array element. For the array element case you can use $addToSet:

db.testcol.update(
    {"my_id": "1"},
    {"$addToSet": {"test_list": {"test_id": 2, "test_name": "mmmm"}}})

It will only add the new element to the doc's test_list array field if a matching element isn't already present.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • @PhalguniMukherjee That means you have at least one doc in your collection where `test_list` isn't an array. – JohnnyHK Oct 22 '13 at 19:12
  • "$addToSet" adds a new object in the array,every time,but I don't know whether to add a object or update a field into it. – Phalguni Mukherjee Oct 23 '13 at 05:01
  • @PhalguniMukherjee Not sure what might be going on, but as the docs say: _The $addToSet operator adds a value to an array only if the value is not in the array already_ – JohnnyHK Oct 23 '13 at 05:07