如何操作聚合管道中的日期字段? [英] How can I manipulate a date field in an aggregation pipeline?

查看:66
本文介绍了如何操作聚合管道中的日期字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置从日期字段到一天开始的时间

I'm trying to set the time from a Date field to the start of the day

function getDate(date){ return new Date(date.getYear(), date.getMonth(), 
date.getDate(), 0,0,0); }
...
{"$project" : {
    "_id"   : getDate("$dt"),
...

  • 如果我发送"$dt",则在传递字符串时会得到TypeError: date.getYear is not a function

    • If I send "$dt" I get TypeError: date.getYear is not a function as I'm passing a string,

      如果删除引号,我得到Error: "$dt is not defined"

      If remove the quotation marks, I get Error: "$dt is not defined",

      那么如何将日期对象传递给函数?

      So how do I pass the date object to the function?

      推荐答案

      MongoDB的聚合管道不支持JavaScript.要为汇总管道中的结果操作日期值,您需要使用日期汇总运算符.

      MongoDB's aggregation pipeline does not support JavaScript. To manipulate date values for results in the aggregation pipeline you need to use Date Aggregation Operators.

      例如:

      db.date.aggregate([
          { $project: {
               _id: { $dateToString: { format: "%Y%m%d", date: "$dt" }}
          }}
      ])
      

      假设您有一个文档,该文档的字段名为dt,日期值为ISODate("2017-07-01T10:01:23.344Z"),结果将如下所示:

      Assuming you have a document with a field called dt with a date value of ISODate("2017-07-01T10:01:23.344Z"), the result would look like:

      {
        "result": [
      
          {
            "_id": "20170701"
          }
      
        ],
        "ok": 1
      }
      

      注意:如果同一天有多个文档,则此方法将在结果中创建重复的_id值.您可能需要投影到其他字段名称,或者使用 $group 阶段,而不是$project阶段,如果您打算合并同一天的值.

      Note: if you have multiple documents for the same day, this approach will create duplicate _id values in your results. You may want to project to a different field name or perhaps use a $group stage instead of $project if your intent is to combine values for the same day.

      这篇关于如何操作聚合管道中的日期字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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