2015-11-30 87 views
0

我有一個名爲notification的集合中的文檔,如下所示。MonogoDB:如何替換數組的對象元素

{ 
"_id" : ObjectId("56438985e68a78f46b1fd9cc"), 
"modulename" : "Admin Control Panel", 
"modulecode" : "acp", 
"eventnames" : [ 
    { 
     "name" : "New user account added", 
     "code" : 100, 
     "_id" : ObjectId("5655fb5d710557d8f7895d94"), 
     "emails" : [ 
      "[email protected]" 
     ] 
    }, 
    { 
     "name" : "User permissions changes", 
     "code" : 200, 
     "_id" : ObjectId("5655fb5d710557d8f7895d93"), 
     "emails" : [ 
      "[email protected]", 
      "[email protected]", 
      "[email protected]" 
     ] 
    } 
] 
} 

我想從eventnames數組與另一對象替換一個對象。比方說,要與下列對象

{ 
     "name" : "New user account added", 
     "code" : 100, 
     "_id" : ObjectId("5655fb5d710557d8f7895d94"), 
     "emails" : [ 
      "[email protected]" 
     ], 
     "template": { 
      "title": "Test Email Title", 
      "body": "Test Email Body" 
     } 
    } 

我怎麼能做到這一點,以取代下列對象

{ 
     "name" : "New user account added", 
     "code" : 100, 
     "_id" : ObjectId("5655fb5d710557d8f7895d94"), 
     "emails" : [ 
      "[email protected]" 
     ] 
    }, 

。謝謝。

+0

的可能的複製[MongoDB的 - 更新中嵌套的數組的對象(http://stackoverflow.com/questions/10522347/mongodb-update-an-object-在嵌套陣列) – joao

回答

2

您不需要在此替換對象。您可以在「模板」字段中只是添加到使用.update()方法與位置$運營商這樣您的條件匹配的子文檔:

db.collection.update(
    { 
     "eventnames": { 
      "$elemMatch": { 
       "name" : "New user account added", 
       "code" : 100,   
       "_id" : ObjectId("5655fb5d710557d8f7895d94") 
      } 
     } 
    }, 
    { 
     "$set": { 
      "eventnames.$.template": {    
       "title": "Test Email Title",    
       "body": "Test Email Body"   
      }  
     } 
    } 
) 

您可以隨時更換您的條件匹配的子文檔。例如在這裏你可以做這樣的事情:

var newObj = { 
    "name" : "New user account added", 
    "code" : 100, 
    "_id" : ObjectId("5655fb5d710557d8f7895d94"), 
    "emails" : [ "[email protected]" ], 
    "template": { "title": "Test Email Title", "body": "Test Email Body" } 
} 

{ "$set": { "eventnames.$": newObj } }