Reputation: 1549
I'm trying to rollup data by time segments for various document elements. I need to present the timestamp for the time segment in the output document, but am having trouble extracting it from the id element. My code is:
var baseDate = new Date(2017, 01, 11, 00, 00, 0);
var startDate = new Date(2017, 01, 11, 00, 00, 0);
var endDate = new Date(2018, 09, 20, 14, 25, 0);
var divisor = 10 * 60 * 1000; // 10 minutes in miliseconds
db.AUDIT.aggregate([
{
$match : {
requestDtsCal : {
$gte : startDate,
$lt : endDate
}
}
}, {
$group : {
_id : { timestamp: {
$subtract : [ "$requestDtsCal", {
$mod : [ {
$subtract : [ "$requestDtsCal", baseDate ]
}, divisor ]
} ]
},
serviceKey: "$serviceKey",
contractKey: "$contractKey",
bindingTemplateKey: "$bindingTemplateKey",
containerKey: "$containerKey"
},
count: {$sum: 1},
contract:
{$first: { name: "$contractName", id: "$contractId", key: "$contractKey"}}
}
}, { $project: {
_id: 1,
contract: 1,
count: 1
}
}
]).pretty();
The output of this is a series of these objects:
{
"_id" : {
"timestamp" : ISODate("2018-01-17T06:00:00Z"),
"serviceKey" : "uddi:soa.com:ws-mex-servicekey",
"contractKey" : "d36ac6d6-7473-11e6-8466-ba5d36e9bcc7:1001",
"bindingTemplateKey" : "uddi:d6e13584-7655-11e6-8911-aed52c780d1b",
"containerKey" : "acb7eb7f-b28e-4ead-944f-ed116d61"
},
"count" : 30,
"contract" : {
"name" : null,
"id" : 1001,
"key" : "d36ac6d6-7473-11e6-8466-ba5d36e9bcc7:1001"
}
}
{
"_id" : {
"timestamp" : ISODate("2018-01-17T06:10:00Z"),
"serviceKey" : "uddi:soa.com:ws-mex-servicekey",
"contractKey" : "d36ac6d6-7473-11e6-8466-ba5d36e9bcc7:1001",
"bindingTemplateKey" : "uddi:d6e13584-7655-11e6-8911-aed52c780d1b",
"containerKey" : "acb7eb7f-b28e-4ead-944f-ed116d61"
},
"count" : 30,
"contract" : {
"name" : null,
"id" : 1001,
"key" : "d36ac6d6-7473-11e6-8466-ba5d36e9bcc7:1001"
}
}
I don't want to output the whole _id element, just the timestamp, but I can't seem to make this work. I tried adding _id.timestamp
to the project element, but this doesn't seem to be valid. This is with Mongo 3.2.11 FYI.
Any tips on how to best generate an output element that contains the timestamp without including the _id?
Update. Per comments, I tried:
{ $project: {
"_id.timestamp": 1,
contract: 1,
count: 1
}
This does result in output with only the timestamp, but it's wrapped in the _id outer element:
{
"_id" : {
"timestamp" : "2018-01-17 05:20:00.000Z"
},
"count" : 32,
"contract" : {
"name" : null,
"id" : 1001,
"key" : "d36ac6d6-7473-11e6-8466-ba5d36e9bcc7:1001"
}
}
Thanks,
Ian
Upvotes: 0
Views: 2349
Reputation: 75914
You can use below project stages which excludes the existing _id and maps the timestamp field from _id into its own field.
Something like
{ $project:{ _id:0, timestamp:"$_id.timestamp", contract:1, count:1 }}
Upvotes: 0