How do I generate a unique _id for MongoDB embedded documents

I cannot for the life of me figure out how to allow MongoDB to generate an _id for embedded documents. I have the following:

{
   "update":"clients",
   "updates":[ {
         "q":{ _id: ObjectId("626eee073b42defbb7dccd65") },
         "u":{"$push":{"projects":{_id:ObjectId(''),"project_title":"New Project"}}}
      } ]
}

It all works, and I can add the embedded object. I can even specify my own _id if given the correct format. However if I leave _id blank like "u":{"$push":{"projects":{_id:,"project_title":"New Project"}}}

then it errors out. How do I let MongoDB do its thing? Thanks!

@drew Can you check if new ObjectId() works

{
   "update":"clients",
   "updates":[ {
         "q":{ _id: ObjectId("626eee073b42defbb7dccd65") },
         "u":{"$push":{"projects":{"_id": new ObjectId(),"project_title":"New Project"}}}
      } ]
}

@dancia I copied and pasted your solution, but I still get the error “JSON reader expected a string but found ‘)’.” I wonder if it’s a bug with appsmith, like it’s not able to pass it as a non-string command to MongoDB?

Can you try turning OFF the Smart BSON Substitution option under Query Settings tab and see if the query runs?

@dancia Toggled it, refreshed, still no dice. Same error.

@drew Sorry about that. Have asked someone from the backend engineering team to take a look

@dancia Awesome, thanks!

@drew As per the MongoDB community mongo does not allow the auto creation of unique _id for embedded object/document. So ObjectId() will not work for embedded documents. Discussion is available on : Unique Indexes on embedded documents - Working with Data - MongoDB Developer Community Forums