wscourge
wscourge

Reputation: 11311

Create unique indexes for document's objects stored in an array

How do one create unique indexes for document's objects stored in array?

{
_id: 'documentId',
books: [
  {
    unique_id: 1,
    title: 'Asd',
  },
  {
    unique_id: 2,
    title: 'Wsad',
  }
  ...
 ] 
}

One thing I can think of is autoincrementing. Or is there any mongo way to do so?

Upvotes: 0

Views: 53

Answers (1)

marmor
marmor

Reputation: 28229

if you remove the _id field from your doc, mongo will automatically add one for you, which is:

  1. guaranteed to be unique
  2. contains the timestamp of creation
  3. lots of other features.

see here: https://docs.mongodb.com/v3.2/reference/method/ObjectId/

Looking at the example object again, are you referring to the ids in the books array? If so, you can assign them with ObjectIds as well, just like in the document root's _id field:

doc.books.forEach(x => { x.unique_id = new ObjectId() } );

Upvotes: 2

Related Questions