2017-02-01 31 views
0

我有一个字符串列表colleccion:MongoDB的 - 字符串列表对象列表

{ 
"_id" : "87df7fd8f7df", 
"spaces" : [ 
    "45dfsdf5646sdf44fd", 
    "5d4fdf885sahg6f6fg" 
], 
} 

,我试图用一个对象列表这样的替换:

{ 
"_id" : "ytry45rty4r4y", 
"spaces" : [ 
{ 
    "id" : "123", 
    "role" : "" 
}, 
{ 
    "id" : "321", 
    "role" : "" 
}, 
} 

请帮我创建一个脚本。

+0

请提供更多的信息。你想只是盲目地更换? –

+0

是否要将数组中的每个字符串用作id并将角色租用为空? –

回答

0

你可以做的最简单的事情就是在mongo shell中运行这样的东西。 问题是不够清楚明白你想要做什么的映射,但在一般的代码将是这样的:

db.testCollection.find().snapshot().forEach(function (elem) { 
 
\t if (!(elem && elem.spaces && elem.spaces.length && typeof elem.spaces[0] === 'string')) { 
 
\t \t print('Unable to update object: ' + elem._id.toString()); 
 

 
\t \t return; 
 
\t } 
 

 
\t var spaceObjects = elem.spaces.map(function (string) { 
 
\t \t return { 
 
\t \t \t id: string, 
 
\t \t \t role: '' 
 
\t \t }; 
 
\t }); 
 

 
\t db.testCollection.update({_id: elem._id}, 
 
\t \t { 
 
\t \t \t $set: {spaces: spaceObjects} 
 
\t \t } 
 
\t); 
 
});

+0

它工作完美。谢谢Antonio! –

+0

不客气:) –

相关问题