Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create ObjectId in Mongo shell?

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?

like image 802
Antoine Avatar asked May 03 '16 06:05

Antoine


People also ask

How does MongoDB generate ObjectId?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record. Syntax: ObjectId(<hexadecimal>).

How is ObjectId generated?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.

What is MongoDB ObjectId?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.

Can we set _id in MongoDB?

If you want to ensure that MongoDB does not create the _id Field when the collection is created and if you want to specify your own id as the _id of the collection, then you need to explicitly define this while creating the collection. When explicitly creating an id field, it needs to be created with _id in its name.


1 Answers

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.

like image 63
khushboo29 Avatar answered Nov 15 '22 03:11

khushboo29