0

I want to use a variable in a js script as below to retrieve lines processed at a certain date. I try to define "obj_start_date" and "obj_end_date" but i'm not able to use the value in the request ....

I've already tried to find a way in the forum but nothing work for me ... thanks in advance if you can help me :)

var result = 0;

var obj_start_date = {};
var start_date = "2016-01-04 00:00:00";
obj_start_date[start_date]=1;

var obj_end_date = {};
var end_date  = "2016-01-04 23:59:59";
obj_end_date[end_date]=1;

var linkNames = db.lines.find({$and:[{'type':{$in:['mobile','voip']}},{'process_time':{$gte:obj_start_date}},{'process_time':{$lte:obj_end_date}}]}).map(function(doc){
  result = result + parseFloat(doc.duration);
});

print( result+ "\r\n");
1
  • Hi @yann! Can you plz help me understand why are you creating that obj_end_date? I'm not 100% sure but I think you can do something like {'process_time':{$gte: start_date}},{'process_time':{$lte: end_date}} so instead of using obj_start_date Commented Jan 8, 2016 at 15:24

1 Answer 1

2

You could simply construct proper date objects to use in the query if the field process_time is a mongo date:

var result = 0,
    start_date = new Date("2016-01-04 00:00:00"),
    end_date = new Date("2016-01-04 23:59:59");

db.lines.find({
    "type": {
        "$in": ['mobile','voip']
    },
    "process_time": {
        "$gte": start_date,
        "$lte": end_date
    }
}).forEach(function(doc){
    result = result + parseFloat(doc.duration);
});

print( result+ "\r\n" );

Or using the aggregation framework:

var pipeline = [
    {
        "$match": {
            "type": {
                "$in": ['mobile','voip']
            },
            "process_time": {
                "$gte": start_date,
                "$lte": end_date
            }
        }
    },
    {
        "$group": {
            "_id": null
            "total_duration": { "$sum": "$duration" }
        }
    }
]

var linkNames = db.lines.aggregate(pipeline).toArray();
if (linkNames.length > 0) { printjson (linkNames[0].total_duration); }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.