Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change field or update fast in MongoDB?

Tags:

mongodb

Document is this

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

i want chane Document like this

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

so i will try this by 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 it's very slow T.T

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't run it. because first solution is still running ....

do you have any fast solution like this job?

like image 993
seapy Avatar asked Aug 09 '11 15:08

seapy


1 Answers

Your second query is broken since it'll overwrite the entire 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'll be at least twice as fast as your original attempt since there you're updating the same document twice, which is not necessary.

like image 89
Remon van Vliet Avatar answered Oct 18 '22 10:10

Remon van Vliet