How to apply a constraint on data fiedlds in mongodb?

30 Views Asked by At

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.

0

There are 0 best solutions below