Search code examples
mongodbmongoosemongodb-querymongodb-update

MongoDB - Updating datatype in nested array for String to Number not working


I tried to update the MongoDB nested arrays data types, It's updated NaN value. Could you please help me out, anyone. Thanks

MongoDB data:

This is my MongoDB data productqtydetails collection.

[{
    "_id" : ObjectId("5d31567ea23d120f087a9ab1"),
    "productId" : ObjectId("5d31567ea23d120f087a9aaf"),
    "sizes" : [ 
        {
            "name" : "4",
            "qty" : 3.0,
            "price" : "1500.0"
        }, 
        {
            "name" : "5",
            "qty" : 6.0,
            "price" : "1600.0"
        }, 
        {
            "name" : "6",
            "qty" : 7.0,
            "price" : "1700.0"
        }
    ]
}
....
]

Mongo Shell Script:

db.productqtydetails.update({
    _id : ObjectId("5d31567ea23d120f087a9ab1")
    },
{
    $set: {"sizes.$[].price": parseFloat("$sizes.$[].price") //Here I used parseInt(), NumberInt also
}
});

Updated MongoDB data:

after ran the script. i got the price : NaN it is updated.

[{
    "_id" : ObjectId("5d31567ea23d120f087a9ab1"),
    "productId" : ObjectId("5d31567ea23d120f087a9aaf"),
    "sizes" : [ 
        {
            "name" : "4",
            "qty" : 3.0,
            "price" : NaN
        }, 
        {
            "name" : "5",
            "qty" : 6.0,
            "price" : NaN
        }, 
        {
            "name" : "6",
            "qty" : 7.0,
            "price" : NaN //need to update "price" : 1700.0
        }
    ]
}
...
]

Solution

  • Firstly, parseFloat is a javascript function and not a MongoDB operator. Means you can use it in a script but not in a MongoDB query/command.

    Secondly, an update command can not have self-reference (means you can not update a field in a document using the same/different field of the very same document).

    In short, you can not do this in a single query. You need two queries, first to fetch and second to update.

    db.productqtydetails.find({_id : ObjectId("5d31567ea23d120f087a9ab1")}).forEach(function(data) {
        var sizes = data.sizes;
        for(var i = 0; i < sizes.length; i++) {
            sizes[i]["price"] = parseFloat(sizes[i]["price"]);
        }
    
        db.productqtydetails.update(
            {"_id": data._id},
            {"$set": {"sizes": sizes}}
        );
    })