python - 如何使用mongoengine只查询mongo库的部分字段, 而不是全部字段?

 Aaron阿龙_1947_446 发布于 2022-10-28 22:48

一般使用mongoengine会查询符合条件的所有的文档(即文档里的所有字段都会查询出来),现在只想查出文档里的部分字段, 并且保持查询效率不能降低

问题补充:这里提到的问题是使用django + mongoengine模块来查询mongodb数据库, 不是直接使用类似pymongo这样的模块来查询,如何查出部分字段, 并保持较高效率?

2 个回答
  • # comments - skip 5, limit 10
    Page.objects.fields(slice__comments=[5, 10])

    QuerySet类的fields方法可以只获取 所需字段

    2022-10-30 04:03 回答
  • 用find的第二个参数。
    数据

    {
        "_id" : ObjectId("56ceaff4a442fd22fec343ce"),
        "edit_info" : {
            "edited_on" : ISODate("2010-02-25T07:40:36.017Z"),
            "edited_by" : NumberLong(137),
            "original" : ObjectId("56ceaff4a442fd22fec343ce"),
            "previous" : null
        },
        "type" : "problem",
        "schema_version" : 1
    }
    

    查询语句

    db.getCollection('modulestore.definitions').find({_id:ObjectId("56ceaff4a442fd22fec343ce")})

    查询结果

    {
        "_id" : ObjectId("56ceaff4a442fd22fec343ce"),
        "block_type" : "problem"
    }

    读多写少的情况建索引。

    2022-10-30 04:03 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有