-3

Is it possible to fetch selective fields from mongo collections.

Say if my collections is

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]"}

Query to list only Name and SUbjects fields:

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

Not sure if this a duplicate, but i did not get anything similar so posting it.

Rachel
  • 247
  • 6
  • 19

1 Answers1

1

You have to define projection part of .find() method to specify which fields should be returned. You alsow have to explicitly exclude _id, try:

col.find({}, { "_id": 0, "Name": 1, "Subjects": 1 })
mickl
  • 48,568
  • 9
  • 60
  • 89