MongoDB-更新或在数组中插入对象 [英] MongoDB - Update or Insert object in array

查看:915
本文介绍了MongoDB-更新或在数组中插入对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下收藏

{
    "_id" : ObjectId("57315ba4846dd82425ca2408"),
    "myarray" : [ 
             {
                userId : ObjectId("570ca5e48dbe673802c2d035"),
                point : 5
             },
             {
                userId : ObjectId("613ca5e48dbe673802c2d521"),
                point : 2
             },        
     ]
}

这些是我的问题

如果userId不存在,我想插入myarray,应该将其附加到myarray.如果userId存在,则应将其更新为指向.

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.

db.collection.update({
  _id : ObjectId("57315ba4846dd82425ca2408"), "myarray.userId" :  ObjectId("570ca5e48dbe673802c2d035")
},{
   $set: {"myarray.$.point": 10}
})

但是,如果userId不存在,则什么也不会发生.

But if userId doesn't exist, nothing happens.

db.collection.update({
  _id : ObjectId("57315ba4846dd82425ca2408")
},{
  $push: {"myarray": {userId: ObjectId("570ca5e48dbe673802c2d035"), point: 10}}
})

但是如果userId对象已经存在,它将再次推送.

But if userId object already exists, it will push again.

在MongoDB中执行此操作的最佳方法是什么?

What is the best way to do this in MongoDB?

推荐答案

尝试一下

db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $pull: {"myarray.userId": ObjectId("570ca5e48dbe673802c2d035")}}
)
db.collection.update(
    { _id : ObjectId("57315ba4846dd82425ca2408")},
    { $push: {"myarray": {
        userId:ObjectId("570ca5e48dbe673802c2d035"),
        point: 10
    }}
)

说明: 第一个语句$pull中的_id = ObjectId("57315ba4846dd82425ca2408")

Explination: in the first statment $pull removes the element with userId= ObjectId("570ca5e48dbe673802c2d035") from the array on the document where _id = ObjectId("57315ba4846dd82425ca2408")

在第二个$push中插入 该对象{ userId:ObjectId("570ca5e48dbe673802c2d035"), point: 10 }在同一数组中.

In the second one $push inserts this object { userId:ObjectId("570ca5e48dbe673802c2d035"), point: 10 } in the same array.

这篇关于MongoDB-更新或在数组中插入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆