Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$gte and $lte in mongoose with multiple condition

Am I using $gte and $lte wrongly with other condition? I got empty array, but when I do just user_email:req.bodu.user_email I'm able to get all the data.

function firstDayOfMonth() {
  var d = new Date(Date.apply(null, arguments));
  d.setDate(1);
  return d.toISOString();
}

function tomorrowDate() {
  var d = new Date();
  d.setDate(d.getDate() + 1)
  return d.toISOString();
}

Users.find({
    "user_email": req.body.user_email,
    "createdAt": {
      "$gte": firstDayOfMonth(),
      "$lte": tomorrowDate()
    }
  },
  function(err, response) {
    if (!err) {
      console.log(response)
      res.json(response);
    }
  });
like image 936
Maria Jane Avatar asked Oct 09 '16 06:10

Maria Jane


People also ask

What is the $GTE operator in mongoose?

The $gte operator is one of the most commonly used operators in a query. This operator returns the documents where the value of the specified field is greater than or equal to the given value. In this article, we will discuss how to use the mongoose $gte operator.

How to use greater than equals to operator in MongoDB?

MongoDB provides different types of comparison operators and greater than equals to operator ($gte) is one of them. This operator is used to select those documents where the value of the field is greater than equals to (>=) the given value. You can use this operator in methods (like, find (), update (), etc.) according to your requirements.

How to check your mongoose version?

After installing the mongoose module, you can check your mongoose version in command prompt using the command. After that, you can just create a folder and add a file for example, index.js as shown below. Database: The sample database used here is shown below:

What is the difference between $GT and $GTE?

It returns all the documents where the value of the age field is greater than or equal to 25. The $gt operator stands for “greater than” operator. It works in the same way as the $gte does, but with a single exception. It only returns the documents where the value of the specified field is greater than the given value.


1 Answers

It should work

I just tested with these docs

/* 1 */
{
    "_id" : ObjectId("57f9cc3dc4ac279a7c539d0f"),
    "TechActivityId" : 0,
    "LicenseId" : 0,
    "created" : "2016-01-01T00:00:00.000Z",
    "StateofActivity" : "State of Activity",
    "TechGId" : "123121134"
}

/* 2 */
{
    "_id" : ObjectId("57f9e674c4ac279a7c539d10"),
    "TechActivityId" : 0,
    "LicenseId" : 0,
    "created" : "2016-10-10T06:28:37.146Z",
    "StateofActivity" : "State of Activity",
    "TechGId" : "1231234"
}

db.getCollection('hola').find({"created":{"$gte":"2016-01-01T00:00:00.000Z","$lte":"2016-10-10T06:28:37.146Z"}})

And I am getting both documents

like image 145
abdulbarik Avatar answered Oct 20 '22 10:10

abdulbarik