1

这是我的 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?如果艺术家存在于给定的艺术家数组索引中,我只希望它更新属性。

4

1 回答 1

0

如果如您所说,您不介意使用多个查询完成操作,则可以$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 }
)
于 2014-09-12T21:00:04.890 回答