Ordered Dictionary in Python: Add to MongoDB

I have a list of two tuples of elements, where the first element is a string (the name of some parameter) and the second element is a float (the value of this parameter). For instance,

thelist = [('costperunit', 200), ('profit', 10000), ('fixedcost', 5000), ('numpeople':300)] 

There are many other such tuples, and the names in the real case are different. I want to add them to the mongoDB database as key: value pairs. This is how I want to add it.

 db.collection.insert( {paramvalues: {'costperunit':200, 'profit':10000, 'fixedcost': 5000, 'numpeople': 300} } ) 

One way to do this:

 dictform = dict(thelist) db.collection.insert( {paramvalues: dictform} ) 

This, however, does not guarantee the order of parameter names and values, since dict changes the order.

I tried

 from collections import OrderedDict dictform = OrderedDict(thelist) db.collection.insert( {paramvalues: dictform} ) 

This maintains the original order of parameter names and values, but inserts parameter names and values ​​into a list of lists.

I am very new to mongoDB and am trying to learn it. Is there a trick in Python or in mongoDB that would achieve what I want? The reason I want the paramvalues key paramvalues in a Mongodb database as a dictionary (or a Javascript object) is because I can then filter the results using the value of some parameter. For example, I can do:

 db.collection.find( {'paramvalues.costperunit': 200} ) 

If you are sure you cannot do this, I would appreciate it if you would let me know.

Thanks.

+4
source share
2 answers

Pymongo offers a subclass of dict, bson.son.SON: http://api.mongodb.org/python/current/api/bson/son.html , which is streamlined for occasions when you need, such as sending commands.

+7
source

Dictations in Python and arrays in Javascript / BSON (MongoDB) are not ordered. Either you store some explicit sort index number as part of dict / array and perform sorting at the application level at that level, or paste your data into a list, which, of course, is sorted.

-4
source

All Articles