批量删除记录的最佳方法?我可以在MongoDB中链接多个删除批量操作吗?

时间:2019-02-04 15:43:00

标签: mongodb

我有一个集合,其中某些文档碰巧具有相同属性的不同类型。我想根据该标准删除不正确的文档。所以我想我可以做到:

var db = db.getSiblingDB('db'),
	  coll = db.getCollection("coll"),
    bulk = coll.initializeUnorderedBulkOp();
    /* some stuff in between here and there */
bulk.find(
    { 
        "doc.prop1": { $exists: true } 
    }
).remove();

bulk.find(
    { 
        "doc.prop2":{ 
            $exists: true,
            $isArray: true,
            $elemMatch: { 
                "elem": { $type: "object" }
            } 
        }
).remove();

bulk.execute(); 

在单个批量操作中根据多个查询/过滤器删除记录的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,其中_id的值是String或ObjectId(旧版数据库...)。使用下面的脚本,所有值都转换为ObjectId。使用mongo load加载它。

// find the length of collection (collection name is "documents")

var total = db.documents.find().length();
print("found " + total + " documents"); 

// Now find all the items that need to be updated
var documentCursor = db.documents.find().limit(total);

var toBeDeleted = [];

documentCursor.forEach(function(doc) {
    print("Starting with item # " + total);
    var oldId = doc._id; // store old id
    print(" --> oldId : ", oldId);

    try {
        doc._id = new ObjectId();
        db.documents.insert(doc);
        print("new id: ", doc._id);
        toBeDeleted.push(oldId);
        total = total - 1;
    } catch (e) {
        print("failed to insert: ", e);
    }
});

// Afterwards delete the old items
try {
    db.documents.deleteMany({ _id: { $in: toBeDeleted } });
} catch (e) {
    print("Failed to delete: ", e);
}


删除是必要的,因为_id无法更新。对于其他属性,我会做类似的事情,然后使用updateMany


  

最近的备份是毫不费力的。我真正喜欢的是,我可以轻松地重新加载该特定集合并重新开始。   登录后,我使用了mlab,他们的文档很快帮助我恢复了收藏集。