1

Below is my MongoDb collection structure:

{
    "_id": {
        "$oid": "61efa44933eabb748152a250"
    },
    "title": "my first blog",
    "body": "Hello everyone,wazuzzzzzzzzzzzzzzzzzup",
    "comments": [{
        "comment": "fabulous work bruhv",
        
        }]
    }
}

Is there a way to auto generate ids for comments without using something like this:

db.messages.insert({messages:[{_id:ObjectId(), message:"Message 1."}]}); 

I found the above method from the SO question:

mongoDB : Creating An ObjectId For Each New Child Added To The Array Field

But someone in the comments pointed out that:

"I have been looking at how to generate a JSON insert using ObjectID() and in my travels have found that this solution is not very good for indexing. The proposed solution has _id values that are strings rather than real object IDs - i.e. "56a970405ba22d16a8d9c30e" is different from ObjectId("56a970405ba22d16a8d9c30e") and indexing will be slower using the string. The ObjectId is actually represented internally as 16 bytes."

So is there a better way to do this?

Tom Brooke
  • 171
  • 3
  • 15
  • [How to generate a unique ObjectId inside an update or aggregation](https://stackoverflow.com/questions/70028674/how-to-generate-a-unique-objectid-inside-an-update-or-aggregation) – YuTing Jan 29 '22 at 05:05

0 Answers0