2013-03-19 65 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