How to change the type of a field?

后端 未结 13 2047
北荒
北荒 2020-11-22 15:10

I am trying to change the type of a field from within the mongo shell.

I am doing this...

db.meta.update(
  {\'fields.properties.default\': { $type :         


        
相关标签:
13条回答
  • 2020-11-22 15:29

    For string to int conversion.

    db.my_collection.find().forEach( function(obj) {
        obj.my_value= new NumberInt(obj.my_value);
        db.my_collection.save(obj);
    });
    

    For string to double conversion.

        obj.my_value= parseInt(obj.my_value, 10);
    

    For float:

        obj.my_value= parseFloat(obj.my_value);
    
    0 讨论(0)
  • 2020-11-22 15:30

    What really helped me to change the type of the object in MondoDB was just this simple line, perhaps mentioned before here...:

    db.Users.find({age: {$exists: true}}).forEach(function(obj) {
        obj.age = new NumberInt(obj.age);
        db.Users.save(obj);
    });
    

    Users are my collection and age is the object which had a string instead of an integer (int32).

    0 讨论(0)
  • 2020-11-22 15:32

    I need to change datatype of multiple fields in the collection, so I used the following to make multiple data type changes in the collection of documents. Answer to an old question but may be helpful for others.

    db.mycoll.find().forEach(function(obj) { 
    
        if (obj.hasOwnProperty('phone')) {
            obj.phone = "" + obj.phone;  // int or longint to string
        }
    
        if (obj.hasOwnProperty('field-name')) {
         obj.field-name = new NumberInt(obj.field-name); //string to integer
        }
    
        if (obj.hasOwnProperty('cdate')) {
            obj.cdate = new ISODate(obj.cdate); //string to Date
        }
    
        db.mycoll.save(obj); 
    });
    
    0 讨论(0)
  • 2020-11-22 15:32
    You can easily convert the string data type to numerical data type.
    Don't forget to change collectionName & FieldName.
    for ex : CollectionNmae : Users & FieldName : Contactno.
    

    Try this query..

    db.collectionName.find().forEach( function (x) {
    x.FieldName = parseInt(x.FieldName);
    db.collectionName.save(x);
    });
    
    0 讨论(0)
  • 2020-11-22 15:33

    To convert a field of string type to date field, you would need to iterate the cursor returned by the find() method using the forEach() method, within the loop convert the field to a Date object and then update the field using the $set operator.

    Take advantage of using the Bulk API for bulk updates which offer better performance as you will be sending the operations to the server in batches of say 1000 which gives you a better performance as you are not sending every request to the server, just once in every 1000 requests.

    The following demonstrates this approach, the first example uses the Bulk API available in MongoDB versions >= 2.6 and < 3.2. It updates all the documents in the collection by changing all the created_at fields to date fields:

    var bulk = db.collection.initializeUnorderedBulkOp(),
        counter = 0;
    
    db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
        var newDate = new Date(doc.created_at);
        bulk.find({ "_id": doc._id }).updateOne({ 
            "$set": { "created_at": newDate}
        });
    
        counter++;
        if (counter % 1000 == 0) {
            bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
            bulk = db.collection.initializeUnorderedBulkOp();
        }
    })
    // Clean up remaining operations in queue
    if (counter % 1000 != 0) { bulk.execute(); }
    

    The next example applies to the new MongoDB version 3.2 which has since deprecated the Bulk API and provided a newer set of apis using bulkWrite():

    var bulkOps = [];
    
    db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) { 
        var newDate = new Date(doc.created_at);
        bulkOps.push(         
            { 
                "updateOne": { 
                    "filter": { "_id": doc._id } ,              
                    "update": { "$set": { "created_at": newDate } } 
                }         
            }           
        );     
    })
    
    db.collection.bulkWrite(bulkOps, { "ordered": true });
    
    0 讨论(0)
  • 2020-11-22 15:33

    To convert int32 to string in mongo without creating an array just add "" to your number :-)

    db.foo.find( { 'mynum' : { $type : 16 } } ).forEach( function (x) {   
      x.mynum = x.mynum + ""; // convert int32 to string
      db.foo.save(x);
    });
    
    0 讨论(0)
提交回复
热议问题