Modifying query results Operations
Sorting and Limiting Query Results
Sort
We specify the query and then a field that contains the parameter to sort with the following flag:
- 1: ascending order
- -1: descending order
Limit
We specify the maximum results we want to get from a query:
db.companies
.find({ category_code: "music" })
.sort({ number_of_employees: -1, _id: 1 })
.limit(3);
Skip
Skips certain number of documents in a query result. Useful por pagination.
If the previous query is runned with the followind dataset:[
{ _id: 1, name: "Laptop", price: 1000 },
{ _id: 2, name: "Mouse", price: 20 },
{ _id: 3, name: "Keyboard", price: 50 },
{ _id: 4, name: "Monitor", price: 300 },
{ _id: 5, name: "Headphones", price: 80 }
]
We will get:
[
{ _id: 3, name: "Keyboard", price: 50 },
{ _id: 4, name: "Monitor", price: 300 },
{ _id: 5, name: "Headphones", price: 80 }
]
Returning Specific Data from a Query
Projections
Projections allow us to determine which fields we want to retrieve from a query result. We cannot exclude and include fields in the same projection, except if the _id
field.
Include
We can include fields in the result using a projection {field_name:1}
:
Exclude
We can exclude fields in the result using a projection {field_name:0}
:
Counting Documents in a Collection
Count number of documents that match a specify query: