搜尋

首頁  >  問答  >  主體

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

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

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

PHP中文网PHP中文网2888 天前568

全部回覆(2)我來回復

  • 大家讲道理

    大家讲道理2017-04-17 17:47:04

    用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"
    }

    讀多寫少的情況建索引。

    回覆
    0
  • ringa_lee

    ringa_lee2017-04-17 17:47:04

    # comments - skip 5, limit 10
    Page.objects.fields(slice__comments=[5, 10])

    QuerySet類別的fields方法可以只取得 所需欄位

    回覆
    0
  • 取消回覆