Mongodb $ne 日期查询未按预期工作 [英] Mongodb $ne date query not working as expected

查看:51
本文介绍了Mongodb $ne 日期查询未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收集了以下数据.当我使用 db.collection.find({endDate: {$ne: new Date()}}) 时,它还显示了当前日期的结果,即 2018 年 7 月 5 日".

I have collection with Below data. While I am using db.collection.find({endDate: {$ne: new Date()}}) it's also showing result of current date which is "05 JULY 2018".

{ 
    "_id" : "GMDJcQMfs8j8EP9EE", 
    "endDate" : ISODate("2018-07-05T14:59:08.794+0000")
}
{ 
    "_id" : "GMDJcQMfs12233", 
    "endDate" : ISODate("2020-02-21T00:00:00.000+0000")
}
{ 
    "_id" : "GMDJerrr8j8EP9EE", 
    "endDate" : ISODate("2020-02-21T00:00:00.000+0000")
}
{ 
    "_id" : "rrrJcQMfs8j8EP9EE", 
    "endDate" : ISODate("2020-02-21T00:00:00.000+0000")
}

请看图片

推荐答案

您可以通过将日期转换为字符串、添加具有相同格式的当前日期、将两者进行比较并过滤相同的结果来实现:

you can do this by transforming your date to string, adding current date with same format, comare both and filter identical results :

db.test1.aggregate(
    [
        {
            $project: {
                endDate:1,
                endDateFormatted:{$dateToString: {date:"$endDate",format:"%Y-%m-%d"}},
                current:{$dateToString: {date:new Date(),format:"%Y-%m-%d"}}
            }
        },
        {
            $project: {  ab: {$cmp: ['$endDateFormatted','$current']},endDate:1}
        },
        {
            $match: {ab:{$ne:0}}
        },
        {
        $project: {
           endDate:1
        }
    },
    ]
);

输出:

{ 
    "_id" : "GMDJcQMfs12233", 
    "endDate" : ISODate("2020-02-21T01:00:00.000+0100")
}
{ 
    "_id" : "GMDJerrr8j8EP9EE", 
    "endDate" : ISODate("2020-02-21T01:00:00.000+0100")
}
{ 
    "_id" : "rrrJcQMfs8j8EP9EE", 
    "endDate" : ISODate("2020-02-21T01:00:00.000+0100")
}

这篇关于Mongodb $ne 日期查询未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆