mongodb:将整数转换为日期 [英] mongodb: convert integer to date

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

问题描述

文档集合中的日期字段由yyyymmdd格式的整数表示:例如20160407.有没有一种方法可以将其转换为日期,作为汇总管道的一部分,以便可以按相应的星期数将文档分组?

A date field in a document collection is represented by an integer in the yyyymmdd format: e.g. 20160407. Is there a way to convert it to a date as part of an aggregate pipeline so that it could be used to group documents by the corresponding week number?

推荐答案

在聚合管道中不可能.这里的一般前提是将数字表示形式转换为其等效的字符串,然后循环执行更新.对于循环,您需要手动迭代

Not possible within the aggregation pipeline. The general premise here would be to convert the numerical representation to its string equivalent, then do the update in a loop. For looping, you would need to manually iterate the cursor returned by the find() method by either using the forEach() method or the cursor method next() to access the documents.

在循环中,首先将字段转换为字符串格式,然后转换为对语言环境不敏感的日期格式,例如"2016-04-07".一旦获得格式,就可以使用该格式创建一个新的ISODate对象,并使用

Within the loop, convert the field first to a string format, then to a locale insensitive date format like "2016-04-07". Once you get the format then create a new ISODate object with that and update the field using the $set operator, as in the following example where the field is called created_at and currently holds the date in the specified numerical format YYYYMMDD:

var cursor = db.collection.find({"created_at": {"$exists": true, "$type": 1 }}); 
while (cursor.hasNext()) { 
    var doc = cursor.next(),
        dateStr = doc.created_at.toString(),
        dateStr.match(/(\d{4})(\d{2})(\d{2})/),
        betterDateStr = match[2] + '-' + match[3] + '-' + match[1];
    db.collection.update(
        {"_id" : doc._id}, 
        {"$set" : {"created_at" : new ISODate(betterDateStr)}}
    ) 
};


为提高性能,尤其是在处理大型馆藏时,请利用 批量API ,用于批量更新,因为您将以1000个批量发送操作到服务器,这是因为您没有将每个请求都发送到服务器,因此可以提供更好的性能,每1000个请求中只有一次.


For improved performance especially when dealing with large collections, take advantage of using the Bulk API for bulk updates as you will be sending the operations to the server in batches of say 1000 which gives you a better performance as you are not sending every request to the server, just once in every 1000 requests.

以下内容演示了这种方法,第一个示例使用MongoDB版本>= 2.6 and < 3.2中可用的Bulk API.它更新所有 通过将created_at字段更改为日期字段

The following demonstrates this approach, the first example uses the Bulk API available in MongoDB versions >= 2.6 and < 3.2. It updates all the documents in the collection by changing the created_at fields to date fields:

var bulk = db.collection.initializeUnorderedBulkOp(),
    counter = 0;

db.collection.find({"created_at": {"$exists": true, "$type": 1 }}).forEach(function (doc) {
    var dateStr = doc.created_at.toString(),
        dateStr.match(/(\d{4})(\d{2})(\d{2})/),
        betterDateStr = match[2] + '-' + match[3] + '-' + match[1];
        newDate = new ISODate(betterDateStr);
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "created_at": newDate}
    });

    counter++;
    if (counter % 1000 == 0) {
        bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
        bulk = db.collection.initializeUnorderedBulkOp();
    }
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }


下一个示例适用于新的MongoDB版本3.2,此版本自


The next example applies to the new MongoDB version 3.2 which has since deprecated the Bulk API and provided a newer set of apis using bulkWrite():

var bulkOps = [];

db.collection.find({"created_at": {"$exists": true, "$type": 1 }}).forEach(function (doc) { 
    var dateStr = doc.created_at.toString(),
        dateStr.match(/(\d{4})(\d{2})(\d{2})/),
        betterDateStr = match[2] + '-' + match[3] + '-' + match[1];
        newDate = new ISODate(betterDateStr);
    bulkOps.push(         
        { 
            "updateOne": { 
                "filter": { "_id": doc._id } ,              
                "update": { "$set": { "created_at": newDate } } 
            }         
        }           
    );     
})

db.collection.bulkWrite(bulkOps);

这篇关于mongodb:将整数转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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