【问题标题】:Why is my MongoDb query inserting an embedded document on Update?为什么我的 MongoDb 查询在更新时插入了嵌入文档?
【发布时间】:2014-09-13 05:00:04
【问题描述】:

这是我的 MongoDB 查询:

db.events.update({date:{$gte: ISODate("2014-09-01T00:00:00Z")}},{$set:{"artists.$.soundcloud_toggle":false}},{multi:true,upsert:false})

显然我不能使用“artists.$.soundcloud_toggle”来更新艺术家数组中的所有艺术家文档:

"$操作符可以更新第一个匹配的数组元素 使用 $elemMatch() 运算符指定的多个查询条件。 http://docs.mongodb.org/manual/reference/operator/update/positional/"

我很高兴多次运行查询来更改数组的索引,以便在与查询匹配的每个事件中设置每个艺术家的 soundcloud_toggle 属性,例如

artists.0.soundcloud_toggle
artists.1.soundcloud_toggle
artists.2.soundcloud_toggle
artists.3.soundcloud_toggle

问题是:当有人说,艺术家数组中只有一个艺术家文档并且我使用“artists.1.soundcloud_toggle”运行查询时,它将使用单个属性将艺术家文档插入到艺术家数组中:

{
   "soundcloud_toggle" : true
},

(我已经声明了“upsert:false”,无论如何默认情况下应该是假的)

当那里没有现有文档时,如何阻止查询插入文档并设置 soundcloud_toggle:false?如果艺术家存在于给定的艺术家数组索引处,我只希望它更新属性。

【问题讨论】:

    标签: mongodb mongodb-update


    【解决方案1】:

    如您所说,如果您不介意使用多个查询完成操作,则可以在过滤器中添加 $exists 条件。

    例如在第 5 次迭代中,更新 index=4 时,添加:"artists.4": {$exists: true},如:

    db.events.update(
        { date: {$gte: ISODate("2014-09-01T00:00:00Z")},
          "artists.4": {$exists: true} },
        { $set:{ "artists.4.soundcloud_toggle" :false } },
        { multi: true, upsert: false }
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 2018-12-13
      • 1970-01-01
      • 2011-04-26
      • 2015-02-06
      • 2012-08-29
      相关资源
      最近更新 更多