MongoDB:用于整合数组的功能

MongoDB: Function to Consolidate Arrays

本文关键字:数组 功能 用于 MongoDB      更新时间:2023-09-26

我有一个大型数据集,其中的文档有时相互交叉引用,有时不相互引用。在我可以基于这些交叉引用进行mapreduce之前,我必须将交叉引用数组设置为对于交叉引用中的每个值都相同。

我在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操作。

因此,获取需要交叉引用的文档列表,并在插入时将它们与文档一起写入。根据需要进行更新,例如,当一个文档被删除或不再引用另一个文档时。