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

查看:36
本文介绍了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 中,从文档中的数组中移除 userId= ObjectId("570ca5e48dbe673802c2d035") 元素,其中 _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天全站免登陆