[英]Is it possible to only get values of specific fields of MongoDB documents?
For example, I have a collection of documents: [{id:1, title:'A'}, {id:2, title:'B'}, ...]
例如,我有一个文档集合:
[{id:1, title:'A'}, {id:2, title:'B'}, ...]
I want to fetch documents based on some conditions, and only get the values of the fields I want instead of the whole object.我想根据某些条件获取文档,并且只获取我想要的字段的值,而不是整个 object。 In SQL, this can be done by
SELECT title FROM documents WHERE year = 2020
在 SQL 中,这可以通过
SELECT title FROM documents WHERE year = 2020
Can I achieve similar results in MongoDB with PyMongo?我可以使用 PyMongo 在 MongoDB 中获得类似的结果吗?
Try projection like this尝试这样的投影
$cursor = $db->inventory->find(
['status' => 'A'],
['projection' => ['item' => 1, 'status' => 1]]
);
.find()
in MongoDB will have this syntax .find(filter_part, projection_part)
, You can try below code in pymongo: .find()
将具有此语法.find(filter_part, projection_part)
,您可以在 pymongo 中尝试以下代码:
Code:代码:
/** As `.find()` returns a cursor you can iterate on it to get values out,
* In projection `_id` is by default included, So we need to exclude it, projection can use True/False or 1/0 */
for eachDocument in collection.find({year : 2020}, {title: True, _id : False}):
print(eachDocument)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.