MongoDB - Update or Insert object in array

后端 未结 7 1954
醉话见心
醉话见心 2020-12-08 04:26

I have the following collection

{
    "_id" : ObjectId("57315ba4846dd82425ca2408"),
    "myarray" : [ 
        {
            use         


        
7条回答
  •  攒了一身酷
    2020-12-08 05:12

    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.

提交回复
热议问题