PyMongo对子字段预测的支持

2024-06-28 16:07:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在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支持子域预测吗?如果是,正确的语法是什么?在


Tags: 文档clientidfieldsupportdbmongodbfind
1条回答
网友
1楼 · 发布于 2024-06-28 16:07:33

为我工作:

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'])))

打印:

^{pr2}$

您将看到“othersubfield”不包含在中,因为它在投影中被省略了。在

相关问题 更多 >