Reputation: 35
My mongo collection has documents with the key tracking.timestamp
and other documents with tracking.soi_timestamp
. Is there a way to use both keys to $group
in one _id as a new combined_timestampfield
field?
_id: {
"date": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": "$tracking.combined_timestampfield"
}
}
Update sample documents:
{
"tracking": {
"timestamp": {
"$date": "2020-06-02T05:33:10.000Z"
}
}
}
...
{
"tracking": {
"soi_timestamp": {
"$date": "2020-06-02T14:23:00.000Z"
}
}
}
desired output:
{
"_id": {
"date": "2020-06-02"
},
"total": 2
}
Upvotes: 1
Views: 275
Reputation: 3529
Use either $project
or $addFields
to pick either soi_timestamp
and timestamp
into a common name field using $ifNull
operator, lets say actualTimeStamp
at the document level.
Then $group
the documents by this new projected/added field:
Query:
db.collection.aggregate([
{
$addFields: {
"actualTimeStamp": {
$ifNull: [
"$tracking.soi_timestamp",
"$tracking.timestamp"
]
}
}
},
{
$group: {
_id: {
"date": {
$dateToString: {
format: "%Y-%m-%d",
date: "$actualTimeStamp"
}
}
},
count: {
$sum: 1
}
}
}
])
OUTPUT:
[
{
"_id": {
"date": "2020-06-02"
},
"count": 2
}
]
Upvotes: 1