How does a unique partial index work inside an array in Mongo

460 views Asked by At

Does a Mongo partial filter work document wide or is it capable of applying to each individual array item?

USE CASE:

Schema

{ references: [
     {source: ObjectId("57dc688a1410a81ba0fcafcd"), sourceId: 1234},
     {source: ObjectId("57dc688a1410a81ba0fcafee"), sourceId: 5678},
]}

I have a Unique Index that says the Source and the SourceId should be unique. This means that no two documents and no single document can have the same Source and SourceId.

I need to make this a partial key because sometimes the SourceId doesn't exist yet. So I want to add the filter: {"references.sourceId" : {"$exists" : true}}

But a document may have multiple references on a single document - one with a sourceId and one without. I want the array item with the sourceId to get indexed and the one one without to be ignored.

What is the proper way to do this? If the filter has to be document wide is there any way to specify to ignore the document if any of the references is missing a sourceId? Currently mongo doesn't accept logical negations in the operators for the partial index filter.

1

There are 1 answers

0
Girish Gupta On

Mongodb provides indexing only on document basis. If a document having an array and the array having multiple fields then there is no restriction on the field to be unique. There can have same values within an array even though you apply unique index on the field with partial expression