w3resource logo


mongodb query from collection on selective fields

Fetch documents from collection with selective fields

rating has average rating 7 out of 10. Total 12 users rated.

<<PreviousNext>>

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"

mongodb query view data

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 :

>db.userdetails.find({"education":"M.C.A."},{"user_id" : 1})

The SQL equivalent code is

Select user_id from userdetails where education="M.C.A.";

Output of the command

mongodb fetch selective fields example1

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 :

>db.userdetails.find({"education":"M.C.A."},{"user_id" : 1,"password":1,"date_of_join":1})

The SQL equivalent code is

Select user_id,password,date_of_join from userdetails where education="M.C.A.";

Output of the command

Fetch more than one fields from collection based on a criteria

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 :

>db.userdetails.find({"education":"M.C.A."},{"user_id" : 0})

Output of the command

Fetch all data except selective field from collection based on a criteria

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."

photo credit: Nomaan! via photopin cc

<<PreviousNext>>