How to select a single field in MongoDB?

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to select a single field in MongoDB?



In my MongoDB, I have a student collection with 10 records having fields name and roll. One record of this collection is:


name


roll


{
"_id" : ObjectId("53d9feff55d6b4dd1171dd9e"),
"name" : "Swati",
"roll" : "80",
}



I want to retrieve the field "roll" only for all 10 records in the collections as we would do in traditional database by using:


SELECT roll FROM student



I went through many blogs but all are resulting in a query which must have WHERE clause in it. For example:


db.students.find({ "roll": { $gt: 70 })



The query is equivalent to:


SELECT * FROM student WHERE roll > 70



My requirement is to find one field only without any condition. So, what is the query operation for that.



Thanks in advance.





db.students.find({"roll": { $gt: 70}) is not equivalent to SELECT roll FROM student WHERE roll > 70
– therealrootuser
Aug 31 '14 at 5:08


db.students.find({"roll": { $gt: 70})


SELECT roll FROM student WHERE roll > 70





Google is your friend: docs.mongodb.org/manual/tutorial/…. Also another section on : SQL to MongoDB Mapping and also useful SQL to Aggregation Mapping. Spend some time reading the documentation. It is useful.
– Neil Lunn
Aug 31 '14 at 5:16





@NeilLunn Thanks for the link SQL to MongoDB Mapping. Don't know how I missed this.
– Shipra Swati
Aug 31 '14 at 6:37







This Link may help you codefari.com/2015/07/projection-in-mongodb.html
– Singh
Feb 26 '16 at 6:18




13 Answers
13



From the MongoDB docs:



A projection can explicitly include several fields. In the following operation, find() method returns all documents that match the query. In the result set, only the item and qty fields and, by default, the _id field return in the matching documents.



db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )



In this example from the folks at Mongo, the returned documents will contain only the fields of item, qty, and _id.


item


qty


_id



Thus, you should be able to issue a statement such as:


db.student.find({}, {roll:1, _id:0})



The above statement will select all documents in the students collection, and the returned document will return only the roll field (and exclude the _id).


roll


_id



If we don't mention _id:0 the fields returned will be roll and _id. The '_id' field is always displayed by default. So we need to explicitly mention _id:0 along with roll.


_id:0


roll


_id


_id:0


roll





Can't seem to Google this, so worth a shot. Do you have to explicitly exclude all the fields that you don't want? Say you only want one field but the document has 10 you have to explictly set 0 for 9 of them? Edit: Nevermind, excluding _id i.e. {field_I_want:1, _id:0} seems to work
– Karl Tryggvason
Oct 11 '16 at 11:07




0


_id


{field_I_want:1, _id:0}





Is it possible to add a field and then update the doc if I use projections?
– chovy
Dec 12 '16 at 23:18



I think mattingly890 has the correct answer , here is another example along with the pattern/commmand



db.collection.find( {}, {your_key:1, _id:0})


db.collection.find( {}, {your_key:1, _id:0})



enter image description here



get all data from one field with _id


db.student.find({}, {roll:1})



SELECT roll FROM student



get all data from one field without _id


db.student.find({}, {roll:1, _id:0})



find specified data using where clause


db.student.find({roll: 80})



SELECT * FROM students WHERE roll = '80'



find a data using where clause and greater than condition


db.student.find({ "roll": { $gt: 70 })



SELECT * FROM student WHERE roll > '70'



Just for educational purposes you could also do it with any of the following ways:



1.


var query = {"roll": {$gt: 70};
var cursor = db.student.find(query);
cursor.project({"roll":1, "_id":0});



2.


var query = {"roll": {$gt: 70};
var projection = {"roll":1, "_id":0};
var cursor = db.student.find(query,projection);



`



Try the following query:


db.student.find({}, {roll: 1, _id: 0}).pretty();



Hope this helps!!



This works for me,


db.student.find({},{"roll":1})



no condition in where clause i.e., inside first curly braces.
inside next curly braces: list of projection field names to be needed in the result and 1 indicates particular field is the part of the query result



getting name of the student


student-details = db.students.find({{ "roll": {$gt: 70} },{"name": 1, "_id": False})



getting name & roll of the student


student-details = db.students.find({{ "roll": {$gt: 70}},{"name": 1,"roll":1,"_id": False})



If u want to retrieve the field "roll" only for all 10 records in the collections.
Then try this.



In MongoDb :



db.students.find( { } , { " roll " : { " $roll " })



In Sql :



select roll from students


db.student.find({}, {"roll":1, "_id":0})



This is equivalent to -



Select roll from student





db.student.find({}, {"roll":1, "name":1, "_id":0})



This is equivalent to -



Select roll, name from student



Use the Query like this in the shell:



1. Use database_name


database_name


e.g: use database_name



2. Which returns only assets particular field information when matched , _id:0 specifies not to display ID in the result


_id:0


db.collection_name.find( { "Search_Field": "value" },
{ "Field_to_display": 1,_id:0 } )



In mongodb 3.4 we can use below logic, i am not sure about previous versions



select roll from student ==> db.student.find(!{}, {roll:1})



the above logic helps to define some columns (if they are less)



For better understanding I have written similar MySQL query.


Selecting specific fields



MongoDB : db.collection_name.find({},{name:true,email:true,phone:true});



MySQL : SELECT name,email,phone FROM table_name;


Selecting specific fields with where clause



MongoDB : db.collection_name.find({email:'you@email.com'},{name:true,email:true,phone:true});



MySQL : SELECT name,email,phone FROM table_name WHERE email = 'you@email.com';



Here you go , 3 ways of doing , Shortest to boring :


db.student.find({}, 'roll _id'); // <--- Just multiple fields name space separated
// OR
db.student.find({}).select('roll _id'); // <--- Just multiple fields name space separated
// OR
db.student.find({}, {'roll' : 1 , '_id' : 1 ); // <---- Old lengthy boring way



To remove specific field use - operator :


-


db.student.find({}).select('roll -_id') // <--- Will remove id from result




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).


Would you like to answer one of these unanswered questions instead?

k2L0L3wcFKWkpLN,Thlh2 6wbVrVYbCN3DgBRPMZ79Cg3D fm,v1PlKmBXkklIL
cyT,mSjosOS8pW,6tZFXz74

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results