From 37cbaf64f0cf6c4f5a9f73d72140f54597aa937f Mon Sep 17 00:00:00 2001 From: tactonbishop Date: Thu, 11 Aug 2022 13:30:05 +0100 Subject: [PATCH] Last Sync: 2022-08-11 13:30:05 --- .../Querying_a_collection_with_Mongoose.md | 64 ++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/Databases/MongoDB/Querying_a_collection_with_Mongoose.md b/Databases/MongoDB/Querying_a_collection_with_Mongoose.md index 3775d6f..2396460 100644 --- a/Databases/MongoDB/Querying_a_collection_with_Mongoose.md +++ b/Databases/MongoDB/Querying_a_collection_with_Mongoose.md @@ -45,7 +45,7 @@ Now we will query the collection. This capability is provided via the Mongoose s The various `find` methods return a value that is promisified. -## Return all values in a collection: `find` +## Return values with `find` ```js async function getCourses(){ @@ -54,7 +54,9 @@ async function getCourses(){ } ``` -### Filter values returned +## Filter values returned + +This will return all the published courses where Tosh Gnomay is the author: ```js async function getCourses(){ @@ -62,3 +64,61 @@ async function getCourses(){ console.log(courses) } ``` + +This time we will filter by the same author but we will add additional parameters to distinguish: + +* only the first ten entries (using `.limit(10)`) +* sort ascending by name (using `.sort({name: 1}))` , to descend we would use `-1`) +* only return the properties `name` and `tags` for the item in the collection (using `.select({name: 1, tags: 1})`) + +```js +async function getCourses(){ + const courses = await Course + .find({author: 'Tosh Gnomay', isPublished: true}) + .limit(10) + .sort({name: 1}) + .select({name: 1, tags: 1}) + console.log(courses) +} + +``` + +This returns: + +```js +[ + { + _id: new ObjectId("62f4f07a875cff48827b8731"), + name: 'Java Course', + tags: [ 'java', 'backend' ] + }, + { + _id: new ObjectId("62f4e2527ac4aa2c30d41d24"), + name: 'Javascript Course', + tags: [ 'js', 'frontend' ] + } +] +``` + +> Note that the UUID is always returned, whether we specify it or not. + +## Comparison operators + +The following comparison operators are available in MongoDB: + +| Operator | Function | +|----------|---------------------------| +| `eq` | Equal to | +| `ne` | Not equal to | +| `gt` | Greater than | +| `gte` | Greater than or less than | +| `lt` | Less than | +| `lte` | Less than or equal to | +| `in` | In | +| `nin` | Not in | + +We can employ these comparators within a `.find` filter. For example let's imagine that our `courses` instances have a property of `price`. To filter prices $>= 10 \And \And <= 20$: + +```js +Course.find(({price: {$gte: 10, $lte: 20} })) +``` \ No newline at end of file