MongoDB tutorials
4. Projected fields, limit, skip, and sort – MongoDB tutorials
Video tutorial:
First we will add a document which further have a document inside it, we call it nested documents:
db.users.insert({ "name": { "first": "Adnan", "last": "Afzal" }, "age": 29})
You see that the name field is an object having further 2 fields first and last. Now in order to query the nested document you need to use the dot “.” operator:
db.users.find({ "name.first": "Adnan" })
This will return the record if the first field of name field has value “Adnan”. This is how you can query nested documents in MongoDB. Right now you will see all the fields returned from the query but in some situations you want only specific fields to be returned, for example if you are storing user’s password then you do not want that field to be returned. In that case, you can pass the second parameter in the find() function:
db.users.find({ "name.first": "Adnan" }, { "name": 1 })
Now you will see only name and ObjectId field, ObjectId is generated by MongoDB and it is a unique identifier for each document in MongoDB collection. If you want to hide this ObjectId field too, then you need to pass _id value as 0:
db.users.find({ "name.first": "Adnan" }, { "name": 1, "_id": 0 })
Now if you want to limit the number of records to be fetched, you can use the limit() function after find() function:
db.users.find().limit(2)
This will return 2 records. Similarly, if you want to skip few records, you can use skip() function:
db.users.find().skip(2).limit(2)
This will skip the first 2 records and get the next 2. Now to sort the records, you can use sort() function. It will receive an object with field name as key and 1 or -1 as value. 1 is used to sort the records in ascending order and -1 is used to sort the records in descending order.
db.users.find().sort({ "age": -1 })
This will sort all the documents in the user’s collection sorted by age in descending order (largest to smallest).