What about if we save value as well as it's objectid in the same collection

If we save a field like this

“state”: “State Name”

if we don’t want to run join, is it ok
please mention pros and cons

Hello @Zubair_Rajput,

If I understand correctly, you want to save objectId as string type (hex representation) "640817d74490c6aa49689306", not objectId type ObjectId("640817d74490c6aa49689306"),

Yes you can save, and there is no connection between join and objectId type, you can $lookup by any type of field, but should match the types of properties provided in localField and foreignField,

I would suggest you store objectId in objectId type instead of string (hex representation), there are benefits:

  • objectID values are 12 bytes in length while string (hex representation) occupies around 1 byte per character so in total it would be around 24 bytes
  • index on objectID type is more efficient

You can read more about ObjectID in this doc,

For the sake of understand we can say it is a USER collection.
Actually I am saving with ObjectId, the question was that I want to save both id and it’s value in same document so that I don’t to run lookup. Is there any harm or bad about it.

I would say that is not bad, MongoDB’s rule of thumb is “Data that is accessed together should be stored together”.

1 Like