[英]MongoDB: Function to Consolidate Arrays
我有一個很大的數據集,其中包含文檔,這些文檔有時相互交叉引用,有時卻沒有。 在我可以基於這些交叉引用進行映射縮減之前,必須將交叉引用的數組設置為對交叉引用中的每個值都相同。
我在shell函數中使用它來合並這些數組:
function fixArray2() {
var counter = 0;
// I only want the xref for each field, I don't even want the id
var cursor = db.catalog.find({}, {xref: true, _id: false});
// I don't want to init this inside the loop, worried about memory leaks
var consolidatedArray = [];
while (cursor.hasNext()) {
var xref1 = cursor.next().xref;
// first pass: create a consolidated array when the cross references match
var limitedCursor1 = db.catalog.find({"name":{$in:xref1}});
while (limitedCursor1.hasNext()) {
var doc1 = limitedCursor1.next();
consolidatedArray = consolidatedArray.concat(doc1.xref);
}
consolidatedArray = consolidatedArray.unique();
// now that we have the consolidated array, reset the xref field of the object to it
for (var i=0; i<consolidatedArray.length; i++) {
db.catalog.update({name:consolidatedArray[i]},{$set:{xref: consolidatedArray}},false, true);
}
consolidatedArray.length = 0;
counter++;
if (counter % 1000 == 0) {
print("Processed " + counter + " documents.");
}
}
}
它可以工作,但是我必須經常運行它。 誰能提出改進建議?
如果在將文檔寫入集合時進行了前期工作,則可以避免在以后進行工作時進行這種map-reduce的操作。
因此,獲取應交叉引用的文檔列表,並在插入時將其與文檔一起寫入。 例如,當文檔被刪除或不再引用另一個文檔時,可根據需要進行更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.