BEWARE: You can't have a uniqueness index on a timeseries collection. If you write usage records that MUST be unique, they must be taken care of in the aggregation.
stackoverflow
mongodb timeseries issue
Which then whats the point of using a timeseries DB for normal queries if there are duplicates.
Create Collection
[
{
"create": "usage",
"timeseries": {
"timeField": "date",
"metaField": "meta",
"granularity": "minutes"
}
}
]
[
{
"drop": "usage"
}
]
Indexes
[{
"createIndexes": "usage",
"indexes": [
{
"key": {
"meta.org_id" :1,
"meta.bucket_id" : 1,
"date" : 1
},
"name" : "meta.org_id_1_meta.bucket_id_1_date_1",
"unique": false,
"background": true,
"collation":{
"locale":"en_US",
"strength": 2
}
}
]
}]
[
{
"dropIndexes": "usage",
"index": "meta.org_id_1_meta.bucket_id_1_date_1"
}
]
db.getCollection("usage").insert([
{
date: ISODate("2020-01-03T05:00:00.000Z"),
count: 5,
meta:{org_id:"ORG1234a",bucket_id:"ABCD"},
},
{
date: ISODate("2020-01-03T05:00:01.000Z"),
count: 6,
meta:{org_id:"ORG1234a",bucket_id:"ABCD"},
}])
db.getCollection("usage").aggregate([
{
$match: {
"meta.org_id": "ORG1234a",
"meta.bucket_id": "ABCD"
}
},
{
$group:
{
_id: "$meta.org_id",
total: {
$sum: "$count"
}
}
}
])