Fetch documents from collection with selective fields
has average rating
7
out of 10.
Total 12 users rated.
Description
In this page, we are going to discuss how to fetch data for specific columns or except a specific column from a collection in MongoDB.
Our database name is 'myinfo' and our collection name is 'userdetails'. Here, is the collection bellow.
Sample collection "userdetails"
Fetch selective field from collection based on a criteria
If we want to fetch only the "user_id" for all documents from the collection 'userdetails' which hold the educational qualification "M.C.A.", the following mongodb command can be used :
The SQL equivalent code is
Output of the command

The above output shows that, two documents have fetched from the collection "userdetails" but only the data of user_id have appeared for those documents who have the qualification "M.C.A.".
N.B. Here in the example a "1" after "user_id" have introduce for fetching that field. So which fields you want to fetch you have to mention the "field_name" followed by a ":" and a "1". 1 indicates true. Show the example below.
Fetch more than one fields from collection based on a criteria
If we want to fetch the "user_id" , "password" and "date_of_jon" for all documents from the collection 'userdetails' which hold the educational qualification "M.C.A.", the following mongodb command can be used :
The SQL equivalent code is
Output of the command

The above output shows that, two documents have fetched from the collection "userdetails" but only the data of user_id, password and date_of_join have appeared for those documents who have the qualification "M.C.A.".
Fetch all data except selective field from collection based on a criteria
If we want to fetch all data except the "user_id" field for all documents from the collection 'userdetails' which hold the educational qualification "M.C.A.", the following mongodb command can be used :
Output of the command

The above output shows that, two documents have fetched from the collection "userdetails" and all the fields have appeared except the data of user_id, for those documents who have the qualification "M.C.A."

