In a collection, I have a metadata field thats just an array of key-value data for generic data.
[
{ key: "test1": value: "value1" },
{ key: "test2": value: "value2" },
{ key: "test3": value: "value3" },
]
Isit possible to add a partial unique index such that I can only one record with key=someId, value=someId. If not, what might be a good way to index such field for more performant search by key value pairs (or do u recommend a different approach). For example:
{
"name": "xyz",
"metadata": [
{ key: "oid": value: "value1" }
]
},
// This record is valid
{
"name": "abc",
"metadata": [
{ key: "oid": value: "value2" }
]
},
// This record is invalid since value1 is duplicated
{
"name": "123",
"metadata": [
{ key: "oid": value: "value1" }
]
}
UPDATE:
Following @KaushikDas answer, I made an index like suggested
db.collection.metadata.createIndex(
{ metadata: 1 },
{ unique: true,
partialFilterExpression: { 'metadata.key': 'myid' }
}
)
It does prevent me from adding duplicate key values, however, when I try to do a query like
db.getCollection('collname').find({
"metadata" : { $elemMatch: { key: 'myid', value: 'myvalue' } }
}).explain()
It doesnt use the index why is that?