mongodb - create doc if not exist, else push to array

前端 未结 1 864
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 13:15

I have a document in the following form:

{
\"_id\" : ObjectId(\"4d2d8deff4e6c1d71fc29a07\"),
\"user_id\" : \"714638ba-2e08-2168-2b99-00002f3d43c0\",
\"events         


        
相关标签:
1条回答
  • 2020-12-10 13:40

    You can do upserts in Mongo, see "Upserts with Modifiers" from the Mongo doc:

    You may use upsert with a modifier operation. In such a case, the modifiers will be applied to the update criteria member and the resulting object will be inserted.

    The query you need will look like:

    db.events.update( { "user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0" }, 
    { $push : { "events" : { "profile" : 10, "data" : "X"}}}, {"upsert" : true});
    
    0 讨论(0)
提交回复
热议问题