convert to object id type a field in mongodb

PHOTO EMBED

Wed Aug 30 2023 20:30:22 GMT+0000 (Coordinated Universal Time)

Saved by @rickysanta #javascript

// Assuming you have a collection named "yourCollectionName" and a field named "yourFieldName"

// Connect to your MongoDB database
use yourDatabaseName;

// Update the documents in the collection
db.yourCollectionName.find({}).forEach(function(doc) {
    if (typeof doc.yourFieldName === 'string') {
        doc.yourFieldName = ObjectId(doc.yourFieldName); // Convert to ObjectId type
        db.yourCollectionName.save(doc);
    }
});
content_copyCOPY