2014-10-17 48 views
1

我需要更新MongoDB中的子數組的子對象。編輯MongoDB中子數組的子對象

我的文檔:

{ 
    "_id" : ObjectId("5433d63cfafed42c083e0809"), 
    "name" : "Flavio", 
    "desc" : "feature", 
    "US" : [ 
     { 
      "_id" : ObjectId("543ebeb473bc8d243d6b28dc"), 
      "name" : "asdf", 
      "desc" : "asdf", 
      "tasks" : [ 
       { 
        "_id" : ObjectId("544029257266e4841735cde8"), 
        "name" : "hello", 
        "date" : "16/10/2014 05:23:01 pm", 
        "author" : "5424ac37eb0ea85d4c921f8b" 
       }, 
       { 
        "_id" : ObjectId("54410bf33561315021a29e2b"), 
        "name" : "lol", 
        "date" : "17/10/2014 09:30:43 am", 
        "author" : "5424ac37eb0ea85d4c921f8b" 
       } 
      ] 
     } 
    ] 
} 

我需要推一個新的數組US.tasks._id =的ObjectId的任務( 「54410bf33561315021a29e2b」)。更新預計

任務:

{ 
    "_id" : ObjectId("54410bf33561315021a29e2b"), 
    "name" : "lol", 
    "date" : "17/10/2014 09:30:43 am", 
    "author" : "5424ac37eb0ea85d4c921f8b" 
    "points" : [ 
     { 
      "count" : 10, 
      "name": "pt" 
     } 
    ] 
} 

我嘗試:

db.projects.update({ 
    "US.tasks": { 
      $elemMatch: {"_id": ObjectId("544029257266e4841735cde8")} 
    } 
}, { 
    $push: {"US.$.tasks": {"points" : []}} 
}) 


db.projects.update({ 
    "US.tasks": { 
      $elemMatch: {"_id": ObjectId("544029257266e4841735cde8")} 
    } 
}, { 
    $push: {"US.$.tasks.points": {"count" : 10, "name" : "pt"}} 
}) 

但新對象任務對象無法進入。

我如何解決這個問題並獲得我期望的對象?

謝謝!

回答

0

還有另一種方式來做到這一點

db.projects.find(
{ 
    "US.tasks": {$elemMatch: {"_id": ObjectId("544029257266e4841735cde8")}} 
}).forEach(function(item) 
{ 
    var us = item.US;  

    for (var i = 0; i < item.US.length; i++) 
     {    
      var tasks = item.US[i].tasks; 
      for (var i2 = 0; i2 < tasks.length; i2++) 
       { 
        var task = tasks[i2]; 
        var id = task._id;     

        if(id == "544029257266e4841735cde8") 
        { 
         // add new filed 
         task.pointse = {};       
         break; 
        }      
       } 
     } 

    db.projects.save(item);   
});