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.

1 Answer 1

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

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

  • 2
    Thanks. I would also suggest to postpone actual deletion of existing documents until duplication of data completes (i.e. after creating new documents with new _id type), and only then to delete all old documents by: .remove({ $type : x }) More on MongoDB types can be found here: docs.mongodb.org/manual/reference/operator/query/type
    – W.M.
    Commented Jan 6, 2016 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.