鉴于以下文件:
{"classes":3,
"people" : [
{name:John,
age:20,
city:London}
{name:Alice,
age:56,
city:Dublin}
]
}
我的数据库中有很多这样的文档。我只想选择数组中的第一个子文档(此处为John),然后根据第一个子文档中人员的年龄对所有文档进行排序。 我还想只选择类数大于零的整体文档。 我想创建一个排序元组,每个文档中第一个人的年龄,这是我的想法开始:
sorted([(m['age'], m) for m in people.find({"classes":{'$gt':0}},{'people.1':1} )])
感谢您的帮助。
答案 0 :(得分:2)
尝试使用pymongo驱动程序排序(您还可以使用pymongo的DESCENDING
方法的ASCENDING
和sort
参数来控制排序方向:
from pymongo import DESCENDING
people = db.people.find({"classes": {'$gt': 0}}).sort('people.0.age', DESCENDING)
然后使用python创建元组列表。
[(p['people'][0]['age'], p) for p in people]
希望我能正确理解你的问题。
答案 1 :(得分:1)
出于性能原因,您应该在Mongo而不是Python中进行选择和排序。我不知道你是否想要整个子文档在元组中或只是年龄,但这是你将如何做到这一点。
示例数据:
> db.tuple.find({},{_id:0})
{ "classes" : 3, "people" : [ { "name" : "John", "age" : 20, "city" : "London" }, { "name" : "Alice", "age" : 56, "city" : "Dublin" } ] }
{ "classes" : 3, "people" : [ { "name" : "John", "age" : 50, "city" : "London" }, { "name" : "Alice", "age" : 56, "city" : "Dublin" } ] }
{ "classes" : 3, "people" : [ { "name" : "John", "age" : 10, "city" : "London" }, { "name" : "Alice", "age" : 56, "city" : "Dublin" } ] }
{ "classes" : 0, "people" : [ { "name" : "John", "age" : 10, "city" : "London" }, { "name" : "Alice", "age" : 56, "city" : "Dublin" } ] }
{ "people" : [ { "name" : "John", "age" : 15, "city" : "London" }, { "name" : "Alice", "age" : 56, "city" : "Dublin" } ] }
返回按类年龄排序的第一个数组文档> 0:
> db.tuple.find({classes:{$gt:0}}, {_id:0,"people":1,"people":{$slice:1}}).sort({"people.age":1})
{ "classes" : 3, "people" : [ { "name" : "John", "age" : 10, "city" : "London" } ] }
{ "classes" : 3, "people" : [ { "name" : "John", "age" : 20, "city" : "London" } ] }
{ "classes" : 3, "people" : [ { "name" : "John", "age" : 50, "city" : "London" } ] }
返回 年龄的同样的事情:
> db.tuple.find({classes:{$gt:0}}, {_id:0,"people.age":1,"people":{$slice:1}}).sort({"people.age":1})
{ "people" : [ { "age" : 10 } ] }
{ "people" : [ { "age" : 20 } ] }
{ "people" : [ { "age" : 50 } ] }