Mongo查询以从集合中获取选择性字段

时间:2018-11-21 18:17:21

标签: mongodb mongodb-query pymongo

是否有可能从mongo集合中获取选择性字段。

如果我的收藏是

USer_info

{"_id" : ObjectId("56e0a3a2d59feaa43fba49d5", "date":"2018-07-23T00:00:00.000Z", "Name":"ABC", "ID": "1234", "Subjects":"[Maths, Physics, Science, Music]"}
{"_id" : ObjectId("56e0a3a2d5hjhfjtaese45d5", "date":"2018-07-23T00:00:00.000Z", "Name":"BCS", "ID": "3456", "Subjects":"[CS, Physics, Business]"}
{"_id" : ObjectId("56e0a3a2d59feaa43fba49d6", "date":"2018-07-23T00:00:00.000Z", "Name":"XYZ", "ID": "786", "Subjects": "[Agricultar, Business, Music]"}

查询以仅列出“名称”和“对象”字段:

{"Name":"ABC", "Subjects":"[Maths, Physics, Science, Music]"}
{"Name":"BCS", "Subjects":"[CS, Physics, Business]"}
{"Name":"XYZ", "Subjects": "[Agricultar, Business, Music]"}

不确定这是否是重复项,但是我没有收到类似的内容,所以将其发布。

1 个答案:

答案 0 :(得分:1)

您必须定义.find()方法的projection部分,以指定应返回的字段。您还必须明确排除_id,请尝试:

col.find({}, { "_id": 0, "Name": 1, "Subjects": 1 })