python-按一个键的值对mongodb进行排序 [英] python - sort mongodb by the value of one key
问题描述
我有一个具有以下数据结构的集合:
I have a collection with below data structure:
[{name: "123", category: "A"},
{name: "456", category: "B"},
{name: "789", category: "A"},
{name: "101", category: "C"}]
我希望能够通过category
的值对它们进行排序,方法是先指定哪个.例如,按B-> C-> A的顺序对查询进行排序,结果将产生:
I want to be able to sort them according to the value of category
, by specifying which comes first. For example, sorting the query in the order of B->C->A, the result would yield:
[{name: "456", category: "B"},
{name: "101", category: "C"},
{name: "123", category: "A"},
{name: "789", category: "A"}]
使用mongo查询API有什么好的方法吗?我正在使用 mongoengine
Is there any good way of doing so with the mongo query API? I am using mongoengine
推荐答案
做到这一点的最佳方法是使用 $cond
条件运算符,用于向$project
阶段,然后使用
The best way to do this is using the .aggregate()
method and the $cond
conditional operator to add a weight to your documents in the $project
stage then use the $sort
aggregation operator to sort your documents by weight.
pipeline = [{'$project': {'category': 1,
'name': 1,
'w': {'$cond': [{'$eq': ['$category', 'B']},
1,
{'$cond': [{'$eq': ['$category', 'C']},
2,
3]
}]
}
}},
{'$sort': {'w': 1}}
]
Model.aggregate(*pipeline)
使用PyMongo进行演示:
>>> import pprint
>>> import pymongo
>>> client = pymongo.MongoClient()
>>> collection = client['test']['collection']
>>> pipeline = [{'$project': {'category': 1,
... 'name': 1,
... 'w': {'$cond': [{'$eq': ['$category', 'B']},
... 1,
... {'$cond': [{'$eq': ['$category', 'C']},
... 2,
... 3]
... }]
... }
... }},
... {'$sort': {'w': 1}}
... ]
>>> pprint.pprint(list(collection.aggregate(pipeline=pipeline)))
[{'_id': ObjectId('571caa930e4f55302502a361'),
'category': 'B',
'name': '456',
'w': 1},
{'_id': ObjectId('571caa930e4f55302502a363'),
'category': 'C',
'name': '101',
'w': 2},
{'_id': ObjectId('571caa930e4f55302502a360'),
'category': 'A',
'name': '123',
'w': 3},
{'_id': ObjectId('571caa930e4f55302502a362'),
'category': 'A',
'name': '789',
'w': 3}]
这篇关于python-按一个键的值对mongodb进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!