Reputation: 35
The script below is supposed to return a CSV of values I want from mongo, all the data I want is returned, but two items are in a different format, and try as I might I cannot get the value only.
Question 1: The first returned item "$_id", returns ObjectId("5a4b7775d9cc09000185b908") but I want to get ONLY the value 5a4b7775d9cc09000185b908. Every time I try to parse it or use valueOf, it returns a blank value.
Question 2: The 4th item I am requesting is supposed to be a time format of how long something took using the two date values {$subtract: [ "$finished", "$started" ] } (start and finish times). What I get back is NumberLong(5844) which should be just the milisenconds.
Script
var cur=db.submissions.aggregate(
[
{$match: { started: {'$gte': ISODate('2018-01-02 01:01:01.001'), '$lte': ISODate('2018-01-02 13:15:59.999' ) } } },
{$project: {
data: [
"$_id",
{$dateToString: { format: "%Y-%m-%d %H:%M:%S", date: "$started" } },
{$dateToString: { format: "%Y-%m-%d %H:%M:%S", date: "$finished" } },
{$subtract: [ "$finished", "$started" ] },
"$inputs.x12InputFile.size"
]
}
}
]
)
cur.forEach(function(doc) {print(doc.data)})
Current Results
ObjectId("5a4b7775d9cc09000185b908"),2018-01-02 12:13:42,2018-01-02 12:13:48,NumberLong(5844),5322
ObjectId("5a4b77d530391100017d92df"),2018-01-02 12:15:18,2018-01-02 12:15:26,NumberLong(8593),5178
Expected Results
5a4b7775d9cc09000185b908,2018-01-02 12:13:42,2018-01-02 12:13:48,5844,5322
5a4b77d530391100017d92df,2018-01-02 12:15:18,2018-01-02 12:15:26,8593,5178
Any help would be appreciated. I am quite the newbie at scripting mongo queries, so details/examples in responses help if at all possible.
Upvotes: 2
Views: 662
Reputation: 75934
I wouldn't use aggregation framework for formatting results. You can't convert from ObjectId to string in aggregation piepline anyways.
var cursor = db.submissions.find({started:{'$gte': ISODate('2018-01-02
01:01:01.001'),'$lte': ISODate('2018-01-02 13:15:59.999' )}},{started : 1,
finished : 1, "inputs.inputFile.size" : 1});
cursor.forEach( function(doc) {
var arr=[];
arr.push(doc._id.str);
arr.push(doc.started.toISOString());
arr.push(doc.finished.toISOString());
arr.push(doc.finished.getTime() - doc.started.getTime());
print(arr)
});
Upvotes: 2