2017-07-31 55 views
-2

我需要從MongoDB中的不同對象中刪除多個元素,但我的查詢返回以下錯誤:「無法將拉應用到非數組值」。這是我的查詢:

db.getCollection('mediaelements').update(
    { customer: ObjectId("...") }, 
    { $pull: { competitions: { $in: [ '24', '362', '361' ] } } }, 
    { multi: true } 
) 

和元件的結構的一個例子:

{ 
    "_id" : ObjectId("..."), 
    "opts" : { 
     "data" : { 
      "playerSide" : "both", 
      "playerIconPlayer" : "p92985" 
     }, 
     "type" : "playerIcon" 
    }, 
    "language" : null, 
    "network" : "any", 
    "customer" : ObjectId("..."), 
    "file" : "image.png", 
    "type" : "image", 
    "__v" : 0, 
    "ranking" : 1, 
    "competitions" : [ 
     "24", 
     "58", 
     "354", 
     "361" 
    ], 
    "medias" : [] 
} 

在這裏,我想刪除競賽「24」和「361」。

感謝您的幫助

PS:這似乎沒有工作{多:真}: 隨着{:真正的多}:「更新1個在1ms內現有結果」 「不能適用$拉到非數組值「 With $ pullAll: 」$ pullAll需要一個數組參數,但被賦予了一個對象「

也許有一些'比賽'不是數組?我怎麼能將這隻應用於數組?或者歡迎任何其他解決方案。

+0

使用'$ pullAll'代替:https://docs.mongodb.com/manual/reference/operator/update/pullAll/ –

+0

你的做法,是完全在我的箱子裏工作,我有Mongo3.4。請檢查您是否傳遞了正確的對象ID(客戶對象ID) –

+0

它適用於一個元素,如果您有多個元素,則它不起作用。 $ pullAll也不起作用,它會返回以下錯誤「$ pullAll需要一個數組參數,但被賦予了一個對象」 – Psychologist

回答

0
  1. 使用updateMany更新許多文件
  2. 使用$pullAll下降的具體項目
  3. 使用dot notation過濾掉無效的(「非陣列」)的數據。

全部放在一起:

db.getCollection('mediaelements').updateMany(
    { customer: ObjectId("...") }, 
    { "competitions.0": { "$exists": true } }, 
    { $pullAll: { "competitions": [ '24', '362', '361' ] } } 
)