Ordered Spec in PyMongo

最近寫 Python 存取 mongoDB 時注意到一個問題,就是在下 find 時很自然的用了 dict 來下條件,但其實 mongoDB 的 find 會需要注意先後次序,用來跟index 搭 配在某些情況例如 hint,次序是有影響的。PyMongo 在這部份的說明其實蠻模糊 的,相關的文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
pymongo.collection

find(self, *args, **kwargs)

:Parameters:
- `spec` (optional): a SON object specifying elements which
must be present for a document to be included in the
result set


bson.son

class SON(__builtin__.dict)
SON data.

A subclass of dict that maintains ordering of keys and provides a
few extra niceties for dealing with SON. SON objects can be
converted to and from BSON.

__init__(self, data=None, **kwargs)

所以若要保留順序,就要直接用 SON 物件來當 find 的參數。建立的方法跟 dict.items() 傳回來的東西一樣,是 “list of D’s (key, value) pairs, as 2-tuples”

1
2
3
4
5
6
>>> from bson import son
>>> a = son.SON([('a', 1), ('b', 1), ('c', 1), ('d', 1)])
>>> a
SON([('a', 1), ('b', 1), ('c', 1), ('d', 1)])
>>> a.to_dict()
{'a': 1, 'c': 1, 'b': 1, 'd': 1}