简体   繁体   English

如何将字符串转换为日期然后在猫鼬查询中减去日期?

[英]How can convert string to date then subtract date in mongoose query?

Can I subtract string to string with date format? 我可以将字符串减去日期格式的字符串吗?

Example: 例:

I have two fields: request and response (String format: yyyy/mm/dd HH:mm:ss). 我有两个字段:请求和响应(字符串格式:yyyy / mm / dd HH:mm:ss)。

I have record: 我有记录:

{
_id: 1,
request: 2015/12/28 12:10:10,
response: 2015/12/28 12:10:15
}

and expect result: 并期望结果:

{
_id: 1,
duration: 5
}

Can we convert string to date then using $subtract (aggregation) to subtract two value? 我们是否可以将字符串转换为日期,然后使用$subtract (聚合)减去两个值?

I try to search and found nothing yet. 我尝试搜索,但仍未找到任何内容。

To convert the string to date format you would have to iterate the results from a find() operation and update the collection within the loop: 要将字符串转换为日期格式,您必须迭代find()操作的结果,并在循环内更新集合:

db.collection.find({}).forEach(function(doc) { 
    db.collection.update(
        { "_id": doc._id }, 
        {
            "$set": { 
                "request": new Date(doc.request), 
                "response": new Date(doc.response) 
            }
        }
    );
});

Perfomance with the above update operation can be compromised if dealing with large collections, however using the Bulk API can streamline the updates for maximised efficiency by reducing the amount of update operations sent to the sever, sending once every 1000 queued operations: 如果处理大型集合,可能会影响上述更新操作的性能,但是使用批量API可以通过减少发送到服务器的更新操作量(每1000个排队的操作发送一次)来简化更新,以实现最大效率:

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

db.collection.find({
    "request": { "$exists": true, "$type": 2 }, 
    "response": { "$exists": true, "$type": 2 }
}).forEach(function(doc) {     
    bulk.find({ "_id": doc._id }).updateOne({
        "$set": { 
            "request": new Date(doc.request), 
            "response": new Date(doc.response) 
        }
    });

    counter++;
    if (counter % 1000 == 0) {
        // Execute per 1000 operations and re-initialize every 1000 update statements
        bulk.execute();
        bulk = db.collection.initializeOrderedBulkOp();
    }
});

// Clean up queues
if (counter % 1000 != 0){
    bulk.execute();
}

Having updated the fields to proper date formats, you can then run the following aggregation pipeline to get the desire results: 将字段更新为正确的日期格式后,您可以运行以下聚合管道以获得所需的结果:

db.collection.aggregate([
    {
        "$project": {
            "duration": { "$subtract": [ "$response", "$request" ] }
        }
    }
])

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

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