Sunday, May 23, 2021

Queries and Query Operators in mongodb using mongoose

find() method returns a DocumentQuery object, similar to promise object.
async function getCourses(){
  const courses = Course.find();
  console.log(courses);
}

Using filters.:
async function getCourses(){
  const courses = Course
    .find({author: 'Mosh',isPublished: true})
    .limit(10)
    .sort({name: 1})//for decending use -1
    .select({name: 1,tags: 1});//to filter columns in final result
  console.log(courses);
}

getCourses();
//generated _id property by default to the documents in mongodb

Query Operators.
1. Comparison Operators
2. Logical Operators

Comparison operators:
  1. eq(equal)
  2. ne(not equal)
  3. gt(greater than)
  4. gte(greater than or equal to)
  5. lt
  6. lte
  7. in
  8. nin(not in)
You can replace above find method with below different kind of arguments using comparison operators.


.find({price: 10})//price = 10
.find({price: {$gte: 10}})// price>=10
.find({price: {$gte: 10, $lte: 20}})// 10<=price<=20
.find({price: {$in: [10,15,20] }})// price = 10 or 15 or 20

Logical Operators: (or, and)
keep the find method empty and call the logical operator as a method.



.find()
.or([{author: 'Mosh'},{isPublished: true}]) // courses authored by Mosh or courses published.

Regular expressions:
.find({author: /pattern/})

.find({author: /^Mosh/i})  //starts with Mosh, i means case-insensitive
.find({author: /Hamedani$/i})//ends with Hamedani
.find({author: /.*Mosh.*/})//conatains Mosh

to count documents
async function getCourses(){
  const courses = Course
    .find({author: 'Mosh',isPublished: true})
    .limit(10)
    .sort({name: 1})
    .count();
  console.log(courses);
}
getCourses();

to implement pagenation.
async function getCourses(){
  const pageNumber = 2;
  const pageSize = 10;

  const courses = await Course
    .find({author: 'Mosh',isPublished: true})
    .skip((pageNumber - 1)*pageSize)
    .limit(pageSize)
    .sort({name: 1})//for decending use -1
    .select({name: 1,tags: 1});//to filter columns in final result
  console.log(courses);
}

A more complex one with multiple operators involved
const Course = mongoose.model('Course',courseSchema);

async function getCourses(){
 return await Course
 .find({isPublished: true})
 .or([{tags:'frontend'},{tags:'backend'}])
 .sort('-price')
 .select('name author price');
}

async function run(){
 const courses = await getCourses();
 console.log(courses);
}

run();

Get all the published courses that are more than or equal to 15 dollars. or have the word 'by' in their title.

const Course = mongoose.model('Course',courseSchema);

async function getCourses(){
 return await Course
 .find({isPublished: true})
 .or([
  {price: {$gte: 15}},
  {name: /.*by.*/i}
 ])
 .sort('-price')
 .select('name author price');
}

async function run(){
 const courses = await getCourses();
 console.log(courses);
}

run();

No comments:

Post a Comment