2013-03-07 84 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") 
}