Mongo change data type

Time:2021-9-19

Mongo writes in quotation marks, resulting in some numeric fields of string type. Modify the field type to numeric type.

db.Report99.find().forEach(
    function(doc){
        db.Report99.update({'_id': doc._id},{$set:{"begin-quantity": parseFloat(doc["begin-quantity"])}}); // Change to floating point number
        db.Report99.update({'_id': doc._id},{$set:{"end-quantity": NumberInt(doc["end-quantity"])}}); //  Change to integer
    }
);

Mongo4.2 + version, the parameters can be as follows:

db.getCollection("my-report").update(
    {
        "begin-quantity": { $type: "string" }
    },
    [{$set: {"begin quantity": {$convert: {input: "$average quantity", to: "double"}}}], // valid type: string|bool|int|long|double|decimal|date|timestamp|objectid
    { multi: true }
)

explain:
1. If the collection name contains special characters, use dB. Getcollection (‘My report ‘)
2. Doc in foreach takes a field value and directly doc.key. If the key contains special characters, Doc [”] is used

This article is composed of blog one article multi posting platformOpenWriterelease!