2017-02-01 30 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

不客氣:) –

相關問題