简体   繁体   English

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

[英]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.

相关问题 检索 mongodb 集合中所有文档的特定字段 - Retrieve specific fields of all documents in mongodb collection 如何将 dict 值添加到字段等于 dict 键的 mongodb 文档中? - How to add dict values to mongodb documents with fields equals dict keys? 使用 TinyDB 仅获取字段值而不是文档 - Get only field values instead of documents with TinyDB MongoDB :: 如何按文档中的字段计数文档? - MongoDB :: How to Count Documents by Fields within the Documents? Firestore 从集合中文档的 get() 中排除特定字段 - Firestore exclude specific fields from get() of documents in collection mongodb 在 python 中记录 treeview 中的值 - mongodb documents values in treeview in python Djangorestframework:是否可以仅反序列化传入JSON的特定字段? - Djangorestframework: is it possible to deserialize only specific fields of incoming JSON? 可以查询嵌入式文档并仅获取那些文档而不是至少一个? - Possible to query for embedded documents and get only those documents rather than where at least one? 尝试在 MongoDB 中使用嵌入式文档字段 - Trying to use Embedded Documents Fields in MongoDB 使用 pymongo 向 mongodb 中的文档添加多个字段 - Adding multiple fields to documents in mongodb using pymongo
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM