I have a collection with objects like this:
{
"_id": "test",
"rows": [
{
"id": "r1",
"blocks": [
{
"id": "b1"
},
{
"id": "b2"
}
]
},
{
"id": "r2",
"blocks": [
{
"id": "b3"
}
]
}
]
}
I would like to add collection validation to enforce unique block ids within rows.blocks so that there are never 2 blocks with the same id in a single document.
This answer on Mongo's JIRA board explains how to set up a query validator to check array property uniqueness using a $size == $setUnion check like this:
db.runCommand({collMod:"coll", validator: {$expr:{$eq:[{$size:"$a.b"},{$size:{$setUnion:"$a.b"}}]}}})
However, it doesn't seem to work for nested arrays like in my example. I tried using this but it didn't block me from saving an invalid document:
{validator: {$expr: {$eq: [{$size: "$rows.blocks.id"}, {$size: {$setUnion: "$rows.blocks.id"}}]}}}
So what's the right way to set up a validator to enforce uniqueness among multiple nested arrays like the example?
_id, row_idwill enforce the uniqueness.