Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create an Index for a document inside array inside document in MongoDB

Let’s say I have this document:

{
  "_id": objectId(),
  "products": [
    {
      "product_id": ""
    }
  ]
}

I would like to make that the key product_id of documents in the array products must be unique for that document in the collection, (i don’t want it to affect other documents in the collection).

I tried to use the next command in mongosh console:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

db.season.createIndex({products.product_id:1},{unique:true})

But it doesn’t work. the console says:

Error: clone(t={}){const r=t.loc||{};return e({loc:new Position("line"in r?r.line:this.loc.line,"column"in r?r.column:……)} could not be cloned.

>Solution :

Unfortunately, that is not possible. The index only works across multiple documents. You can have repeating values within the same document.

See this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading