首页 > 解决方案 > 按日期(年)在数据库中查找文档;

问题描述

我正在尝试对我的数据库进行查询,我有一个包含一些包含日期类型字段的文档的集合,我想查找日期等于我选择的年份的所有文档,最好的方法是什么做吗?

此刻我正在收到这样的文件。

facturasCtrl.filterDates = async (req, res) => {

    facturas = await facturasModel.find({ date: { '$gte': req.body.date1, '$lt': req.body.date2} })
    res.json(facturas); 
}

//date1 = 1.1.2018 //date2 = 31.12.2018

但我认为这种方式根本不正确......有什么方法可以从某个日期找到所有文件?

标签: mongodbmongodb-query

解决方案


You can use $expr with the $year aggregation operator

const year = 2018  

db.collection.find({ "$expr": { "$eq": [{ "$year": "$date" }, year] } })

推荐阅读