Home > Enterprise >  How can I find between two specific datas with MongoDB Query
How can I find between two specific datas with MongoDB Query

Time:04-05

Basicly I would like to find the between two specific dates like March 20 to 30 or age between 15-30. I didn't find any sample for native driver. I am using MongoDB Node Driver, not mongoose so $lte and $gte like this code didn't work.

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var query = { date: { $lte: "2022-04-01" }};
    var dbo = db.db("myDb");

    dbo.collection("info").find(query).toArray(function (err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
}); 

I have a structure like this;

{
    "_id" : ObjectId("6246ff6abff0907a89edd48c"),
    "name" : "name1",
    "age"  : 25,
    "date" : "2022-3-21"
},
{
    "_id" : ObjectId("6246ff917a33f49da8dc74de"),
    "name" : "name2",
    "age"  : 28,
    "date" : "2022-3-28"
},
{
    "_id" : ObjectId("624a213e738b9e8d94c9abad"),
    "name" : "name3",
    "age"  : 35,
    "date" : "2022-4-3"
}

Many thanks.

CodePudding user response:

The type of the "date" field is "string".

If you save it as ISODate. You can query as you say. Sample :

var myDate = new Date("2022-03-18T16:00:00Z");

Query:

var query = { date: { $lte: ISODate("2022-03-18T16:00:00Z") }};

   dbo.collection("info").find(query).toArray(function (err, result) {
         if (err) throw err;
         console.log(result);
         db.close();
     });

Ref: https://www.mongodb.com/docs/manual/reference/method/Date/

  • Related