0

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
        }
    ]
}
...
]
4
  • can you add your schema for more information? Commented Aug 28, 2019 at 10:09
  • Try using NumberDecimal() Commented Aug 28, 2019 at 10:35
  • @vishalpankhaniya I have used the mongo shell Commented Aug 28, 2019 at 14:27
  • @Anban I got the error Error: Input is not a valid Decimal128 value. Commented Aug 28, 2019 at 14:34

1 Answer 1

1

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}}
    );
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.