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

时间:2020-05-11 11:54:04

标签: python database mongodb pymongo

例如,我有一组文档:[{id:1, title:'A'}, {id:2, title:'B'}, ...]

我想基于某些条件来获取文档,并且只获取我想要的字段的值,而不是整个对象。在SQL中,可以通过SELECT title FROM documents WHERE year = 2020

完成

使用PyMongo,我可以在MongoDB中获得类似的结果吗?

2 个答案:

答案 0 :(得分:0)

尝试这样的投影

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

答案 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)