在 Mongo 中选择子文档 [英] Selecting subdocument in Mongo

查看:86
本文介绍了在 Mongo 中选择子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下文档:

{"classes":3,
"people" : [

    {name:John,
    age:20,
    city:London}

    {name:Alice,
    age:56,
    city:Dublin}

]
}

我的数据库中有很多这样的文档.我只想选择数组中的 first 子文档(此处为 John),然后根据第一个子文档中人员的年龄对所有文档进行排序.我还想只选择类数大于零的整体文档.我想用每个文档中第一个人的年龄创建一个排序的元组,这是我的想法:

I have many documents like this in my database. I want to only select the first subdocument in the array (here John), and then sort all my documents with respect to the age of the person in the first subdocument. I also want to only select the overall documents where number of classes is bigger than zero. I want to create a sorted tuple with the age of the first person in each document, this was my idea to start:

sorted([(m['age'], m) for m in people.find({"classes":{'$gt':0}},{'people.1':1}  )])

感谢您的帮助.

推荐答案

尝试用 pymongo 驱动排序(也可以用 DESCENDINGASCENDING 控制排序的方向> pymongo 的 sort 方法的参数):

Try to sort with pymongo driver (you can also control the direction of the sorting with DESCENDING and ASCENDING arguments of the sort method of the pymongo):

from pymongo import DESCENDING
people = db.people.find({"classes": {'$gt': 0}}).sort('people.0.age', DESCENDING)

然后用python创建一个元组列表.

and then create a list of tuples with python.

[(p['people'][0]['age'], p) for p in people]

希望我正确理解您的问题.

Hope i understand your problem correctly.

这篇关于在 Mongo 中选择子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆