0
Array
(
    [_id] => 1
    [OrderId] => 123456_0203_2500001101518267176
    [Items] => Array
       0 =>  Array (
            [ItemId] => "123456"
            [ItemDesc] => "This Item numer 123456"
        ),
       1 =>  Array (
            [ItemId] => "123457"
            [ItemDesc] => "This Item numer 123457"
        ),


)

Array
(
    [_id] => 1
    [OrderId] => 123456_0203_2500001101518267199
    [Items] => Array
       0 =>  Array (
            [ItemId] => "123458"
            [ItemDesc] => "This Item numer 123458"
        ),
       1 =>  Array (
            [ItemId] => "123459"
            [ItemDesc] => "This Item numer 123459"
        ),


)

I want to make ItemId be unique in the document as well as across the document.

Unique index only provides uniqueness across the documents. But, I want to restrict repeating same ItemId within the document as well.

1 Answers1

0

You can use $addToSet while inserting/updating your document. I don't think you will need indexes.

Example of using $addToSet

db.test.update(
   { _id: 1 },
   { $addToSet: {letters: [ "c", "d" ] } }
)

Details: https://docs.mongodb.com/manual/reference/operator/update/addToSet/

Amit Phaltankar
  • 3,341
  • 2
  • 20
  • 37
  • I am not sure, whether this will be useful for me or not.This will be useful while updating a document, right? – Sreekumar TP Mar 05 '18 at 10:13
  • Correct. and as of now there is no easy way to achieve this. I don't know how are you using MongoDB. But there is an unique array plugin available in Mongoose https://www.npmjs.com/package/mongoose-unique-array – Amit Phaltankar Mar 06 '18 at 01:05