2017-05-08 114 views
0

我是Mongodb的新手,並通過Mongodb文檔進行自學習。我有以下情形掙扎,請建議我如何在MongoDB中實現這一點:MongoDB中的嵌套更新

{ 
    "_id" : ObjectId("5a2d123456"), 
    "Name" : "MongoDB", 
    "BookCode" : "ID321", 
    "Issue" : [ 
     { 
      "Name" : "ABC", 
      "Date" : '2016-12-15' 
     }, 
     { 
      "Name" : "DEF", 
      "Date" : '2017-10-01' 
     } 
    ] 
} 

我的方案是: - 如果沒有特別名稱&的bookcode文檔,然後檢查是否有任何Issue.Name存在或不存在相同的名稱,如果存在則更新或在問題下插入新數組。

if exists (Name: 'abc' and BookCode: 'book1') 
    then if exists (Issue.Name: 'DEF') 
     then 
      Update Issue.Date 
     else 
      Insert 
+2

讓我們知道你已經嘗試過 – sidgate

+0

你正在嘗試這在mongo shell或通過一些代碼? –

+0

嘗試mongo shell –

回答

0

我想是這樣的:

db.Books.find({Name:"MongoDB", BookCode:"ID321"}).forEach(function (thisIssue) 
{ 
    thisIssue.Issue.forEach(function (item) 
    { 
     if(item.Name === 'ABC') 
     { 
      item.Date = "201705011315.0" 
     } 
      db.Books.save(thisIssue); 
     } 
    }); 
}); 

工作到一定程度上。 這可以使用UPSERT? 我嘗試了upsert(名稱上的唯一索引,BookCode & Item.Name),但它在Items下插入新的子文檔。