0

I have a mongo collection, each document contains a nested array of objects like the following :

[
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]

I want warehouse field inside instock to be unique with each item document.

Example:

{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "A", qty: 15 } ] }

The previous record shouldn't be inserted as warehouse is not unique withing a single document.

What type of indez should ensure this restriction.

Rajesh Pandya
  • 1,540
  • 4
  • 18
  • 31

1 Answers1

0

The indexes purpose is to speedup of the select queries, not the data validation. This data validation must be implemented in the application layer.

You must avoid the unnecessary indexes, because it slow downs MongoDB. Each index must be examinated on the select query (trying to pick the winning plan) and updated on document insert/update/delete.

Neodan
  • 5,154
  • 2
  • 27
  • 38