0


I'm learning MongoDb, I have many documents like this in my collection:

enter image description here

And I want to update my cust_id field from String to ObjectId. I can use Compass to change type but I have very many documents. I've read from Mongo document but still don't understand. Can you show me how to do this on my document for me to understand clearly.
Thank you very much!

Tomato
  • 759
  • 2
  • 14
  • 26

2 Answers2

1

There are a few posts here that hint at the solution.

db.students.find().forEach(function(obj) {
  obj.cust_id = ObjectId(obj.cust_id);
  db.students.save(obj);
});

I tested this in Atlas 4.0.6 and it worked well. I don't know, however, how well this technique will scale to a large dataset.

Just replace students with your own collection name.

It'sNotMe
  • 1,184
  • 1
  • 9
  • 29
0

I have tested this function turning a string into number and it worked well

db.students.find().forEach(obj =>{
   obj.code_number= parseInt(obj.code_number);
   db.students.save(obj);
});

You can also create a new collection with the results to keep the original data and check the results

db.students.find().forEach(obj=> {
   obj.code_number= parseInt(obj.code_number);
   db.students_new.save(obj);
});
blissini
  • 545
  • 1
  • 7
  • 18