【问题标题】:$set and $push for multiple documents in the same mongodb update$set 和 $push 用于同一 mongodb 更新中的多个文档
【发布时间】:2018-05-28 00:49:47
【问题描述】:

我努力更新同一个集合的多个文档,这些文档需要将字段添加到 JSON“根”,以及一个名为 logs 的现有数组的新对象。

我正在尝试这个

db.getCollection('charges').
update({'supports.dest':ObjectId("xyz"), 
      date:{
                          $gte: new Date(2017, 11),
                          $lt: new Date(2017, 12) 
           },
      "status": {$nin : ["Captured"]  
                }
        },
      {$set: {"status": "BillingSuspended",  
           "replacedStatus":"Captured"} 
      },
      {multi:true},
      {$push : 
        {logs : {"replacedStatus" : "Captured" ,
                 date: new Date ('2017-12-13T22:00:00.000Z') 
                }
        }
      }
)

我在下面收到此错误,我尝试取出 multi:true 但随后我失去了允许我同时更新多个文档的 multi 属性。我想要一个在 Robomongo 上运行的查询。如果您能帮助我,我将不胜感激。

错误:

[Failed to execute script.

Error: Fourth argument must be empty when specifying upsert and multi with an object. :
DBCollection.prototype._parseUpdate@src/mongo/shell/collection.js:522:1
DBCollection.prototype.update@src/mongo/shell/collection.js:552:18
@(shell):1:1]

1

【问题讨论】:

  • 这能回答你的问题吗? stackoverflow.com/questions/38864917/…
  • 这样的东西应该可以工作{ "supports.dest":ObjectId("xyz"), "date": { "$gte": new Date(2017, 11), "$lt": new Date(2017, 12) }, "status": { "$nin": [ "Captured" ] } }, { "$set": { "status": "BillingSuspended", "replacedStatus": "Captured" }, "$push": { "logs": { "replacedStatus": "Captured", "date": new Date ('2017-12-13T22:00:00.000Z') } } }, { "multi": true }
  • 感谢@Veeram!成功了!
  • 我的另一个问题是如何将状态“Captured”而不是状态传递给“replacedStatus”字段,而是动态传递更新前的状态,你知道我的意思吗?跨度>

标签: javascript mongodb robo3t


【解决方案1】:

你必须这样尝试

db.getCollection('charges').updateMany(
        {
            'supports.dest': ObjectId("xyz"),
            'date': {
                '$gte': new Date(2017, 11),
                '$lt': new Date(2017, 12)
            },
            "status": {
                $nin: ["Captured"]
            }
        },
        {
            $set: {
                "status": "BillingSuspended",
                "replacedStatus": "Captured"
            },
            $push: {
                logs: {
                    "replacedStatus": "Captured",
                    date: new Date('2017-12-13T22:00:00.000Z')
                }
            }
        })

【讨论】:

  • 你可以批准我的回答
  • 已经有更新的弃用警告,提示使用updateMany或updateOne。你能用推送更新很多吗?在文档中,没有推送。谢谢。
猜你喜欢
  • 2012-02-22
  • 2019-05-25
  • 2020-08-23
  • 1970-01-01
  • 2016-11-25
  • 2020-09-08
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
相关资源
最近更新 更多