2013-03-19 46 views
0

在我的集合中,我有一個users字段作爲User集合的數組。在MongoDB中用字符串數組替換嵌入式文檔數組

所以,目前看起來是這樣的:

{ "name" : "Untitled", "users" : [ { "name" : "Ace Ventura",  "datecreated" : "2012-10-05T23:55:56.940Z",  "_id" : "740063fb-79c5-4f7f-96e1-907d6ffb1d16" } ], "datecreated" : "2012-10-05T23:55:56.954Z", "_id" : "e207eaea-89f7-48ae-8ba7-b6aa39db2358" } 

我想,這樣用戶採集的陣列就像變成用戶採集的_id財產的數組進行更新。像這樣:

{ "name" : "Untitled", "users" : ["740063fb-79c5-4f7f-96e1-907d6ffb1d16" ], "datecreated" : "2012-10-05T23:55:56.954Z", "_id" : "e207eaea-89f7-48ae-8ba7-b6aa39db2358" } 

我該如何做到這一點?

在此先感謝。

+0

我假設每個文檔數組都有/可以有多個條目? – 2013-03-19 06:38:17

+0

對,上面例子中的'users'將會有多個對象。 – Gezim 2013-03-19 19:32:56

回答

0

好的,我想通了。然而

db.lists.update(
    {}, 
    { 
    $set: { 
      users: <oldusers._id> 
    }, 
}); 

,事實證明,你不能從update()中引用當前文檔的屬性:

起初,我在想這樣做這樣的事情的。

但是,事實證明,我們可以使用forEach()

db.lists.find().forEach(function (list) { 

    // Define length to ensure we have an array of users 
    var userLength = (list.users && list.users.length) || 0; 

    var (var i = 0; i < userLength; i++) { 
     // Ensure the current user object isn't null or undefined 
     if(list.users[i]) 
      list.users[i] = list.users[i]._id 
    } 

    // Finally, save the list object back. 
    db.lists.save(list) 
}); 

謝謝,+ gipset,你的答案here