HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to convert _id field of all existing documents from type String to Number

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
fieldnumberallconvert_idtypehowexistingfromdocuments

Problem

At one of my collections I have an _id field that stores numbers. The field was defined originally in the Mongoose model as String. However, all the data concerning this field in the collection contains pure integers stored as strings. I want to preserve all the data in my collection while converting the type of this field (and all associated _id's) from type String to type Number. Any suggestions as how to do that? Thanks.

Solution

db.getCollection('test').find().forEach(function (doc) {
    db.getCollection('test').remove({ _id : doc._id});
    tempId = new NumberLong(doc._id);
    doc._id = tempId;
    db.getCollection('test').save(doc);
    } 
);


This will do. You may want to add error handling as per your use case. Also make sure you have backup before migrating.

Code Snippets

db.getCollection('test').find().forEach(function (doc) {
    db.getCollection('test').remove({ _id : doc._id});
    tempId = new NumberLong(doc._id);
    doc._id = tempId;
    db.getCollection('test').save(doc);
    } 
);

Context

StackExchange Database Administrators Q#125037, answer score: 6

Revisions (0)

No revisions yet.