MongoDB - Update or Insert object in array
mongodb
Solution
Try this
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{ $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
{ _id : ObjectId("57315ba4846dd82425ca2408")},
{ $push: {"myarray": {
userId:ObjectId("570ca5e48dbe673802c2d035"),
point: 10
}}
)
Explination: in the first statment `$pull` removes the element with `userId= ObjectId("570ca5e48dbe673802c2d035")` from the array on the document where `_id = ObjectId("57315ba4846dd82425ca2408")`
In the second one `$push` inserts this object `{ userId:ObjectId("570ca5e48dbe673802c2d035"), point: 10 }` in the same array.
Problem
I have the following collection ``` { "_id" : ObjectId("57315ba4846dd82425ca2408"), "myarray" : [ { userId : ObjectId("570ca5e48dbe673802c2d035"), point : 5 }, { userId : ObjectId("613ca5e48dbe673802c2d521"), point : 2 }, ] } ``` These are my questions I want to push into `myarray` if `userId` doesn't exist, it should be appended to `myarray`. If `userId` exists, it should be updated to point. I found this ``` db.collection.update({ _id : ObjectId("57315ba4846dd82425ca2408"), "myarray.userId" : ObjectId("570ca5e48dbe673802c2d035") }, { $set: { "myarray.$.point": 10 } }) ``` But if `userId` doesn't exist, nothing happens. and ``` db.collection.update({ _id : ObjectId("57315ba4846dd82425ca2408") }, { $push: { "myarray": { userId: ObjectId("570ca5e48dbe673802c2d035"), point: 10 } } }) ``` But if `userId` object already exists, it will push again. What is the best way to do this in MongoDB?