Pymongo, data recording order in mongodb

0

I am using the pymongo module, to record data in a mongodb collection. But, when I go to review the data, I find that they are not recorded in the order in which I wrote them. If I insert them directly from the mongodb shell, there are no problems. I have read that by default both insert_one and insert_many, they record the data in the same order as it is written, but I do not know where the problem is? I'm using the latest version of module 3.4.0 and the version of mongo 2.6.11 (the one with the ubuntu repository).

my code

from pymongo import MongoClient

serverdb = MongoClient('10.10.10.10', 27017)
db = serverdb.ERP
coleccion = db.FichaCliente
coleccion.insert_one({'1 nombre':'Antonio', '2 telefono':999999999, '3 email':'[email protected]'})
serverdb.close()

Any idea why?

    
asked by Jesús 11.12.2016 в 16:16
source

1 answer

0

If you want to maintain a specific order you must use a container that preserves the order, dict does not do it.

In the standard library there is a container OrderedDict that does.

from collections import OrderedDict

...
datos = {'1 nombre':'Antonio', '2 telefono':999999999, '3 email':'[email protected]'}
coleccion.insert_one(OrderedDict(sorted(datos.items(), key=lambda t: t[0]))

In this example, you would sort the data according to the key of each dictionary element.

    
answered by 11.12.2016 в 20:25