是否可以只获取MongoDB文档的特定字段的值?

问题描述 投票:0回答:1

例如,我有一个文档的集合,我想根据一些条件来获取文档,并且只获取我想要的字段的值,而不是整个对象。[{id:1, title:'A'}, {id:2, title:'B'}, ...]

我想根据一些条件来获取文档 只获取我想要的字段的值,而不是整个对象。在SQL中,可以通过以下方式实现 SELECT title FROM documents WHERE year = 2020

我可以在MongoDB中用PyMongo实现类似的结果吗?

python database mongodb pymongo
1个回答
0
投票

试试这样的投影

$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1]]
);

0
投票

.find() 在MongoDB中会有这样的语法 .find(filter_part, projection_part), 你可以在pymongo中尝试以下代码。

代码 :

/** 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)
© www.soinside.com 2019 - 2024. All rights reserved.