Skip to main content
 首页 » 编程设计

python之PyMongo 支持子场投影

2024年10月01日7xing901022

在 MongoDB 中,我可以执行 projections在子字段上。例如,db.collection.find({},{"field.subfield":1, "_id":0}) 将返回所有文档并仅显示指定的子字段,并隐藏任何其他输出中的字段。

PyMongo 做 support预测,但似乎不适用于子领域。下面给出了示例代码。

from pymongo import MongoClient 
client = MongoDB() 
client.db.collection.find(projection=['field1','field2.subfield']) 

所以我的问题是:PyMongo 是否支持子字段投影?如果是,那么正确的语法是什么?

请您参考如下方法:

对我有用:

from pymongo import MongoClient 
client = MongoClient() 
client.db.collection.drop() 
client.db.collection.insert_one({ 
    'field1': 1, 
    'field2': { 
        'subfield': 'sub', 
        'othersubfield' : 'othersub' 
    } 
}) 
 
print(list(client.db.collection.find(projection=['field1','field2.subfield']))) 

这打印:

[{u'field2': {u'subfield': u'sub'}, u'field1': 1, u'_id': ObjectId('58e3d11dca1ce936cf6498c4')}] 

您会发现“othersubfield”不包括在内,因为它已从投影中省略。