如何在MongoDB中判断某个字段的类型是否为ObjectId并将该字段转换为字符串?

How can I find whether the type of a field is ObjectId or not and convert this field to string in MongoDB?

我有一个 collection,里面有超过 300,000 条记录。我犯了一个错误,其中一些记录有这样的错误字段:

"ParticipantId" : ObjectId("56578b12aa9c5817303f306f"),

但是该字段应该是字符串类型。某些记录具有这样的正确字段:

"ParticipantId" : "56578b12aa9c5817303f306f",

我想做的是找到记录有错误的字段并将它们的值更改为字符串。感谢您的帮助。

您需要使用 $type operator to find documents where type of "ParticipantId" is ObjectId and update those using "bulk" 操作和 .str 属性。

var bulk = db.collection.initializeOrderedBulkOp();
var count = 0;

db.collection.find({'ParticipantId': { '$type': 7 } } ).forEach(function(doc) {
    bulk.find({ '_id': doc._id }).updateOne({
        '$set': { 'ParticipantId': doc.ParticipantId.str }
    });
    count++;
    if (count % 100 === 0) {
        // Execute per 100 operations and re-init
        bulk.execute();
        bulk = db.collection.initializeOrderedBulkOp();
    }
})

// Clean up queues
if (count > 0) bulk.execute();

您可能还想将 "ParticipantId" 更改为 ObjectId,其中 "ParticipantId" 是字符串。

db.collection.find( { 'ParticipantId': { '$type': 2 }}).forEach(function(doc) {
    bulk.find( { '_id': doc._id } ).updateOne( {
        '$set': { 'ParticipantId': ObjectId(doc.ParticipantId) }
    });
    count++;
    if ( count % 100 === 0 ) {
        // Execute per 100 operations and re-init
        bulk.execute();
        bulk = db.collection.initializeOrderedBulkOp();
    }
})

// Clean up queues
if ( count > 0 ) bulk.execute();

在 2.6 之前的版本中,您需要遍历光标和 .update() 您的文档。

db.collection.find( { 'ParticipantId': { '$type': 7 } } ).forEach(function(doc) {
    db.collection.update( 
        { '_id': doc._id }, 
        { '$set': { 'ParticipantId': ObjectId(doc.ParticipantId) } }
    );
} )