0

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.

5
  • The schema validation works on the structure of a single document rather than across the collection. Instead, what you can do is only record the sensor in the document and have a separate collection for sensor_type which maintains a unique index on sensor. 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? Commented Jan 19, 2024 at 9:50
  • So, I don't think it would be possible directly on the DB, via validation or indexes. Would require some client-side code during record creation or processing. Commented Jan 19, 2024 at 9:53
  • In general MongoDB is a schema-less database, thus there is nothing build in. You would need to ensure this at application level. Commented Jan 19, 2024 at 10:00
  • Have you tried out the schema validation? Commented Jan 19, 2024 at 10:19
  • I've checked the page for the schema validation, there there are some examples for numeric numbers, but I would not know from where to start in my case, which keyword should be used? Commented Jan 19, 2024 at 10:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.