Python中的有序字典:添加到MongoDB

Cur*_*arn 5 python mongodb

我有一个包含两个元素元组的列表,其中第一个元素是一个字符串(某个参数的名称),第二个元素是一个float(该参数的值).例如,

thelist = [('costperunit', 200), ('profit', 10000), ('fixedcost', 5000), 
           ('numpeople':300)]
Run Code Online (Sandbox Code Playgroud)

还有更多这样的元组,名称在实际案例中有所不同.我想将这些作为键:值对添加到mongoDB数据库.这是我想要添加它的方式.

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

一种方法是:

dictform = dict(thelist)
db.collection.insert( {paramvalues: dictform} )
Run Code Online (Sandbox Code Playgroud)

但是,这不会确保参数名称和值dict的顺序会改变顺序.

我试过了

from collections import OrderedDict 
dictform = OrderedDict(thelist)
db.collection.insert( {paramvalues: dictform} )
Run Code Online (Sandbox Code Playgroud)

这将维护参数名称和值的原始顺序,但是,将参数名称和值作为列表列表插入.

我是mongoDB的新手,并试图学习它.在Python或mongoDB中是否有一个可以实现我想要的技巧?我想将paramvaluesMongodb数据库中的键值作为字典(或Javascript对象)的原因是我可以使用某个参数的值来过滤结果.例如,我可以这样做:

db.collection.find( {'paramvalues.costperunit': 200} )
Run Code Online (Sandbox Code Playgroud)

如果你确定无法做到这一点,如果你让我知道,我将不胜感激.

谢谢.

Bre*_*ams 7

Pymongo提供了dict的子类,bson.son.SON:http://api.mongodb.org/python/current/api/bson/son.html ,可以根据需要发送命令,例如发送命令.

  • 我不得不使用它,因为我遇到了一个奇怪的情况,我的_id字段的排序(它不是一个对象ID,它是一个字典)将导致MongoDB重复条目.虽然这个问题不是一个很好的解决方案 - 它似乎迄今为止已经奏效并可能对其他人有所帮助. (2认同)