简体   繁体   English

在MongoDB中将字符串转换为ISODate

[英]Convert string to ISODate in MongoDB

I am new to MongoDB and I am stuck on the String to Date conversion. 我是MongoDB的新手,我坚持使用String to Date转换。 In the db the date item is stored in String type as "date":"2015-06-16T17:50:30.081Z" 在db中,日期项以String类型存储为"date":"2015-06-16T17:50:30.081Z"

I want to group the docs by date and calculate the sum of each day so I have to extract year, month and day from the date string and wipe off the hrs, mins and seconds. 我想按日期对文档进行分组并计算每天的总和,因此我必须从日期字符串中提取年,月和日,并擦除小时,分钟和秒。 I have tried multiple way but they either return a date type of 1970-01-01 or the current date. 我尝试了多种方式,但它们要么返回1970-01-01的日期类型,要么返回当前日期。

Moreover, I want to convert the following mongo query into python code, which get me the same problem, I am not able to call a javascript function in python, and the datetime can not parse the mongo syntax $date either. 此外,我想将以下mongo查询转换为python代码,这给我带来了同样的问题,我无法在python中调用javascript函数,并且datetime也无法解析mongo语法$date

I have tried: 我努力了:

new Date("2015-06-16T17:50:30.081Z")
new Date(Date.parse("2015-06-16T17:50:30.081Z"))
etc...

I am perfectly find if the string is given in Javascript or in Python, I know more than one way to parse it. 我很好地发现如果字符串是用Javascript或Python给出的,我知道解析它的方法不止一种。 However I have no idea about how to do it in MongoDB query. 但是我不知道如何在MongoDB查询中执行此操作。

  db.collection.aggregate([
                    {
                        //somthing
                    },
                    { 
                        '$group':{
                            '_id':{ 
                                'month':  (new Date(Date.parse('$approTime'))).getMonth(), 
                                'day': (new Date(Date.parse('$approTime'))).getDate(), 
                                'year':  (new Date(Date.parse('$approTime'))).getFullYear(),
                                'countries':'$countries'
                            },
                             'count': {'$sum':1}

                    }
                }
])

If you can be assured of the format of the input date string AND you are just trying to get a count of unique YYYYMMDD, then just $project the substring and group on it: 如果您可以确定输入日期字符串的格式并且您只是想获得唯一YYYYMMDD的计数,那么只需$ item上的子字符串和组:

var data = [
        { "name": "buzz", "d1": "2015-06-16T17:50:30.081Z"},
        { "name": "matt", "d1": "2018-06-16T17:50:30.081Z"},
        { "name": "bob", "d1": "2018-06-16T17:50:30.081Z"},
        { "name": "corn", "d1": "2019-06-16T17:50:30.081Z"},
      ];

db.foo.drop();
db.foo.insert(data);

db.foo.aggregate([
     { "$project": {
         "xd": { "$substr": [ "$d1", 0, 10 ]}
         }
 },
 { "$group": {
             "_id": "$xd",
             "n": {$sum: 1}
         }
     }
              ]);

{ "_id" : "2019-06-16", "n" : 1 }
{ "_id" : "2018-06-16", "n" : 2 }
{ "_id" : "2015-06-16", "n" : 1 }

Starting Mongo 4.0 , you can use "$toDate" to convert a string to a date: 启动Mongo 4.0 ,您可以使用"$toDate"将字符串转换为日期:

// { name: "buzz", d1: "2015-06-16T17:50:30.081Z" }
// { name: "matt", d1: "2018-06-16T17:50:30.081Z" }
// { name: "bob",  d1: "2018-06-16T17:50:30.081Z" }
// { name: "corn", d1: "2019-06-16T17:50:30.081Z" }
db.collection.aggregate(
  { $group: {
    _id: { $dateToString: { date: { $toDate: "$d1" }, format: "%Y-%m-%d" } },
    n: { $sum: 1 }
  }}
)
// { _id: "2015-06-16", n: 1 }
// { _id: "2018-06-16", n: 2 }
// { _id: "2019-06-16", n: 1 }

Within the group stage, this: 在小组赛阶段,这个:

  • first converts strings (such as "2015-06-16T17:50:30.081Z" ) to date objects ( ISODate("2015-06-16T17:50:30.081Z") ) using the "$toDate" operator. 首先使用"$toDate"运算符将字符串(例如"2015-06-16T17:50:30.081Z" )转换为日期对象( ISODate("2015-06-16T17:50:30.081Z") )。

  • then converts the converted date (such as ISODate("2015-06-16T17:50:30.081Z") ) back to string ( "2015-06-16" ) but this time with this format "%Y-%m-%d" , using the $dateToString operator. 然后将转换后的日期(例如ISODate("2015-06-16T17:50:30.081Z") )转换回字符串( "2015-06-16" ),但这次使用此格式"%Y-%m-%d" ,使用$dateToString运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM