How to change the type of a field?

后端 未结 13 2323
北荒
北荒 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: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 });
    

提交回复
热议问题