1

I want to update an array containing lat,lng values.my update query from python is given below.

client.mydb.mycoll.update({"_id":123},{'$push':{"loc":{"lng":77.77,"lat":12.12}}} )

the collection already have some value in "loc" array as follows

{ "_id" : 123, "loc" : [    {   "lng" : 77.6104193,     "lat" : 12.9264116 } ], "name" : "myname" }

the problem with update query is that it store the new "loc" element as

{ "_id" : 123, "loc" : [ { "lng" : 77.6104193, "lat" : 12.9264116 },{"lat":12.12,"lng":77.77} ], "name" : "myname" }

I need to store loc data in the order "lng" fist and then "lat".so that later, I can query using $near operator ({loc:{$near:[77.77,12.12]}}).python dictionary always store key value pair sorted according to key.how can I do it?

sajith
  • 2,564
  • 8
  • 39
  • 57

2 Answers2

1

I suggest changing the structure slightly to match that from the MongoDB manual:

coordinates : [ <longitude> , <latitude> ]

so you'll end up with something like this:

{ "_id" : 123, "loc" : [ [77.6104193, 12.9264116], [77.77, 12.12] ], "name" : "myname" }

MongoDB keeps the order of the array, but does not guarantee preserving the order of object's fields (See this answer to a similar question).

Community
  • 1
  • 1
chitty
  • 317
  • 1
  • 5
  • 18
  • I can't do that,because there is already data in the table using php code.I am moving from php to python – sajith Apr 30 '14 at 10:49
1

After some research I found OrderedDict in python doc.

from collections import OrderedDict

client.mydb.mycoll.update({"_id":123},{'$push':{"loc":OrderedDict((("lng",77.77),("lat":12.12)))}} )
sajith
  • 2,564
  • 8
  • 39
  • 57