Suppose I have a timeseries mongodb collections, similar to the one proposed in the official website, with a structure that might look like:
[
{
"timestamp": 1,
"metadata": {"sensor": "A", "type": "temperature"},
"value": 18
},
{
"timestamp": 2,
"metadata": {"sensor": "A", "type": "temperature"},
"value": 20
},
{
"timestamp": 2,
"metadata": {"sensor": "B", "type": "humidity"},
"value": 30
},
{
"timestamp": 3,
"metadata": {"sensor": "B", "type": "humidity"},
"value": 40
}
]
Clearly, a sensor it's not going to change its type. So on the collection I would like a constraint that checks that a given sensor must have always the same type.
Is it possible to use this constrain on mongo db collection? With indexes I can check for uniqueness, so I was thinking there is something similar for this case, but I don't know if it can be done in a validator.
sensorin the document and have a separate collection forsensor_typewhich maintains a unique index onsensor. So it would be some amount of normalisation. One document per sensor, specifying its type. And in the main collection, you would only store the sensor's name, and not it's type. Otoh, one could argue that if the type never changes, does it need to be validated? Or would a never-changing-'reference' to the type be enough?