2014-09-12 35 views
1

這是我的MongoDB的查詢:爲什麼我的MongoDb查詢在Update上插入嵌入式文檔?

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

顯然,我不能用「藝術家$ 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「,默認情況下應該是false)

如何停止查詢插入文檔並設置soundcloud_toggle:如果沒有現有文檔,則爲false?如果藝術家存在於給定的藝術家數組索引中,我只希望它更新屬性。

回答

0

如果像您所說的那樣,您不介意使用多個查詢完成操作,則可以將$exists條件添加到您的過濾器。

E.g.在第5次迭代中,當更新索引= 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 } 
)