How to quickly change a field or update in MongoDB?

The document is

{title:"here", lat:123.4512, lng:36.3423, time:"2011-01-02"}

I want a chane document like this

{title:"here", {latlng: {lat:123.4512, lng:36.3423}}, time:"2011-01-02"}

so I will try this using the mongodb console.

db.coll.find().forEach(function(u){
  u.latlng = {"lat":u.lat, "lng":u.lng};
  db.coll.save(u);
  db.coll.update(u, {$unset:{"map_x1":1, "map_y1":1}});
})

but he is very slow TT

I think another solution

db.coll.find().forEach(function(u){
  db.coll.update(u, {{"latlng" : {"lat":u.lat, "lng":u.lng}}, $unset:{"lat":1, "lng":1}});
})

but I can not start it. because the first solution is still working ....

Do you have a quick fix like this one?

+5
source share
1 answer

Your second request is broken, as it will overwrite the whole document, use $ set:

db.coll.find().forEach(function(u){
  db.coll.update(u, {$set:{"latlng" : {"lat":u.lat, "lng":u.lng}}, $unset:{"lat":1, "lng":1}});
})

This will be at least twice as fast as your initial attempt, as you are updating the same document twice, which is optional.

+10
source

All Articles