Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a single field for all documents in a MongoDB collection?

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

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

I want to retrieve the field roll only for all 10 records in the collection 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 a single key only without any condition. So, what is the query operation for that.

like image 913
Shipra Swati Avatar asked Aug 31 '14 05:08

Shipra Swati


People also ask

Which query object selects all documents in a MongoDB collection?

A compound query can specify conditions for more than one field in the collection's documents. Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query selects the documents in the collection that match all the conditions.

Which is the required field for all MongoDB documents?

The _id Field In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

How do I fetch all documents in MongoDB?

Connect to a database using the getDatabase() method. Get the object of the collection from which you want to retrieve the documents, using the getCollection() method. Retrieve the iterable object containing all the documents of the current collection by invoking the find() method.


1 Answers

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.


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

db.students.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).

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.

like image 66
therealrootuser Avatar answered Oct 16 '22 15:10

therealrootuser