-1
[{
      "id": 5f6af7bd3f06d50018f28680,
      "image": "https://images-na.ssl-images-amazon.com/images/I/51FQpz-zY1L._SL1024_.jpg",
      "name": "Mac book",
      "price": "150",
      "description": "Apple MacBook Air",
      "rating": 4,
    },
    {
      "id": 5f6af7bd3f06d50018f28682,
      "image": "https://static.acer.com/up/Resource/Acer/Laptops/Swift_7",
      "name": "Dell Laptop",
      "price": "250",
      "description": "Find solace in your love for riding when you cruise",
      "rating": 4,
    }]

In This I want to Change Datatype Of All Object of json Mongodb which is price.

Actually Price is String But i want to convert it to Number dynamically.

turivishal
  • 34,368
  • 7
  • 36
  • 59
  • It would help if you could provide some code showing how you are getting the JSON object you provided, and what code in node is "dynamically" handling said JSON. Without that it's hard to provide a good solution that fits your use case. – tengen Sep 23 '20 at 16:04

3 Answers3

0
db.my_collection.find({price: {$exists: true}}).forEach(function(obj) {
  obj.price = new NumberInt(obj.price);
  db.my_collection.save(obj);
});
Aditya Sawant
  • 193
  • 1
  • 3
0
let data = my_schema.find();
data.map((item) => {
    my_schema.findOneAndUpdate({_id: item._id}, {price: Number(item.price)}})
})
  • 3
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Tyler2P Aug 13 '21 at 12:03
-1

If i understand you correctly , you retrieve array of object from db where pricing field is string and after it you need convert it to numbers ?

  1. Why just not store it as number ?
  2. You can convert it use .map function just after retrieve or if you use mongoose you can do it in post hook in same way.