将字符串转换为日期并得到差异 [英] Convert string to date and get difference

查看:49
本文介绍了将字符串转换为日期并得到差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在食物"模式 -mongodb 中很少有这样的数据记录

I have few data records like this in 'food' schema -mongodb

{
    "_id": "5b220199acbec1409cbf84dd",
    "Name": "Mongo",
    "ID_No": "BA1233",
    "Content": "Bottle",
    "No_packages": 5,
    "No_items": 6,
    "Qty": 30,
    "Mfg": "2018-05-27",
    "Exp": "2018-06-30",
    "__v": 0
  }

我想获取日期差(Exp-today Date)小于30的数据集.我使用以下命令进行了尝试.但是没有用.

I want to get the data set where the date difference(Exp-today Date) is less than 30. I tried it using the following command. But it didn't work.

db.food.find({$lt: { $subtract: [ Date() , Exp ],"30"}}  )

推荐答案

您需要先使用 $dateFromString (聚合)将日期从字符串转换为日期格式,然后 $redact(聚合) 消除不匹配的文档

You need to use first $dateFromString (aggregation) convert date from string to date format and then $redact (aggregation) to eliminates the unmatched documents

db.collection.aggregate([
  { "$addFields": {
    "date": {
      "$dateFromString": {
        "dateString": "$EXP"
      }
    }
  }},
  { "$redact": {
    "$cond": [
      { "$lt": [
        { "$divide": [
          { "$subtract": [new Date(), "$date"] },
          1000 * 60 * 60 * 24
        ]},
        30
      ]},
      "$$KEEP",
      "$$PRUNE"
    ]
  }}
])

这篇关于将字符串转换为日期并得到差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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