如何使用 MongoDB 查询在两个特定数据之间找到

How can I find between two specific datas with MongoDB Query

基本上我想找到两个特定日期之间的时间,例如 3 月 20 日到 30 日或 15-30 岁之间的年龄。我没有找到本机驱动程序的任何示例。 我正在使用 MongoDB 节点驱动程序,而不是 mongoose 所以 $lte 和 $gte 这样的代码不起作用。

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();
    });
}); 

我有这样的结构;

{
    "_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"
}

非常感谢。

“日期”字段的类型为“字符串”。

如果将其保存为 ISODate。你可以按你说的查询。 样本:

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

查询:

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();
     });

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