Querying with Object ID vs Querying with array

I am migrating from another service and changing structure of the database a bit. I already have unique IDs attached to every data group I have and I couldn’t decide if I use this IDs as an ObjectID or inside the document as an array.

Would setting them as ObjectID help with querying performance?

Thanks a lot in advance.


ObjectId is a special data format of 12-byte that consists of:

  • A 4-byte timestamp, representing the ObjectId’s creation, measured in seconds since the Unix epoch.
  • A 5-byte random value generated once per process. This random value is unique to the machine and process.
  • A 3-byte incrementing counter, initialized to a random value.

You should check if your current unique IDs are compatible with this. One advantage of having ObjectId is that you can also do the sort based on it, since it have creation date info inside it.

I would recommend to go with ObjectId if you don’t have to do bigger code refactor because of the change. :smiley:

1 Like

So I can’t just set a random 9 (or 10) digit number as the object ID? Do I get it right?

Thanks a lot for your response.


You don’t have to specify anything. If you don’t specify _id explicitly, Mongo will automatically set it as unique ObjectId. :smiley:

1 Like

You may use anything value for the field _id, a number, a date or a string, even an object but not an array. The only restriction is that is has to be unique within the collection. It has to be unique because all collections comes with a default index on the _id field. You may even have different type within the same collection.

Here are some example:

mongosh test> c.find()
  { _id: 369 },
  { _id: '369' },
  { _id: ISODate("2022-04-09T18:12:37.203Z") },
  { _id: { user: 'steevej', domain: 'gmail.com' } },
  { _id: ObjectId("6251cdb3347f73b0e4852b62") }

So, yes setting you existing unique IDs as the _id will help performance because you get an index by default.

You probably cannot convert your unique (9 to 10 random number) IDs to an ObjectId() because it is special as special as explained by @NeNaD but you may certainly use them as is for the value of the _id field.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.