0

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?

2
  • You said unique indexes then auto increment. I am confused. What are you trying to achieve? Commented Nov 17, 2016 at 14:31
  • What I want is for every book in my books[] to have one separated unique property, so I can tell one from another. Consider "Javascript manual" in the library document for example, with another property library_front_window, array storing unique_id of let's say three of seven exisiting. Commented Nov 17, 2016 at 14:36

1 Answer 1

2

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() } );
Sign up to request clarification or add additional context in comments.

4 Comments

Right, but what I want to achieve is to have my unique id on both document and it's array's objects. It isn't there for no reason :).
So, given the situation when I updateOne() my document and $push to the (books) array, what I need to do is simply update the data being pushed (single book) with new property new ObjectId() ?
yes, when creating that new book entry, just assign new ObjectId() to your id field, BTW, it's common practice to use _id as the name of the field, even for internal objects, so I'd create it as { _id : new ObjectId(), title: 'hello' }
All right, thank you very much sir! It works perfectly, just like you said :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.