2013-03-07 86 views
5

我試圖從三重嵌套數組中刪除一個屬性,但沒有成功。下面是我想刪除的數據的一個例子:MongoDb:如何從嵌套數組中取消設置屬性?

Controls: [ 
    {  
     Name: 'ControlNumberOne', 
     Submit: { 
      Executes: [ 
       { 
        Name: 'execute', 
        Type: 0 
       }, 
       { 
        Name: 'anotherExecute', 
        Type: 0 
       } 
      ] 
     } 
    }, 
    {  
     Name: 'ControlNumberTwo', 
     Submit: { 
      Executes: [ 
       { 
        Name: 'anotherFromAnotherControl', 
        Type: 1 
       } 
      ] 
     } 
    } 

] 

我嘗試了以下更新查詢,但沒有一次成功:

  • db.Page.update('Controls.Submit.Executes.Type': { $exists : true } }, { $unset : { 'Controls.Submit.Executes.Type' : 1 } }, false, true);)

  • db.Page.update('Controls.Submit.Executes.Type': { $exists : true } }, { $unset : { 'Controls.$.Submit.Executes.$.Type' : 1 } }, false, true);)

但是,如果我執行db.Page.find('Controls.Submit.Executes.Type': { $exists : true } })我t確實會返回所有仍具有Type屬性的Executes。

這可以實現嗎?謝謝!嵌套的數組的

+0

你'Executes'似乎是一個對象,而不是一個數組。 – madhead 2013-03-07 20:17:18

+0

你是對的我拼錯了......請現在看看它! – faloi 2013-03-08 00:47:38

回答

4

查詢和更新是(還)沒有通過的MongoDB支持直接命令,這必須在客戶端完成:

  • 讀取的原稿入變量
  • 操縱陣列
  • 更新文件,重寫整個陣列

查看吉拉這個問題:https://jira.mongodb.org/browse/SERVER-831和計算器這個線程:Mongo update of subdocs

鑑於你的榜樣,這應該是這樣的:

db.xx.find(
    {'Controls.Submit.Executes.Type': { $exists : true } } 
).forEach(function(doc) { 
    doc.Controls.forEach(function(c) { 
     c.Submit.Executes.forEach(function(e) { 
      if (e.Type != undefined) delete e.Type;   
     }); 
    }); 
    db.xx.update({_id: doc._id},{$set:{Controls:doc.Controls}}); 
}); 

,其結果是:

> db.xx.findOne() 
{ 
    "Controls" : [ 
     { 
      "Name" : "ControlNumberOne", 
      "Submit" : { 
       "Executes" : [ 
        { 
         "Name" : "execute" 
        }, 
        { 
         "Name" : "anotherExecute" 
        } 
       ] 
      } 
     }, 
     { 
      "Name" : "ControlNumberTwo", 
      "Submit" : { 
       "Executes" : [ 
        { 
         "Name" : "anotherFromAnotherControl" 
        } 
       ] 
      } 
     } 
    ], 
    "_id" : ObjectId("5159ff312ee0f7d445b03f32") 
}