6

I'm updating a document with an array of embedded documents, directly in Mongo shell. I would like each of these sub-docs to have an _id field, but these are not created automatically as they are for top-level documents. Is there a way to simply create an new ObjectId in Mongo shell? Something along the lines of (below example is not valid):

"prop": [
  {
    "_id": new ObjectId(), // creates the objectId when executing the line
    "foo": "bar"
  }
]

The main requirement is not having to manually generate random strings for each doc to create. Is that possible?

Antoine
  • 5,055
  • 11
  • 54
  • 82

1 Answers1

8

Yes it is possible. You can generate ObjectId

ObjectId id = new ObjectId();

// or this
ObjectId id = ObjectId.get();

Then it can be used for update doc. Hope it helps.

khushboo29
  • 906
  • 6
  • 16