Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get _id of an inserted document in MongoDB?

say I have a product listing. When I add a new product I save it using something like

var doc=products.Insert<ProductPDO>(p); 

The problem is that I want after this is done to redirect the user to the page with the product. So I need to redirect to say /products/<ObjectID>

However, I see no way of getting the ObjectID right afterwards without manually querying the database and look for a document with all the same fields and such.

Is there an easier way? (also, doc in this instance returns null for some reason)

like image 798
Earlz Avatar asked Jan 03 '11 08:01

Earlz


People also ask

How does the value of _id get assigned to a document?

_id is the primary key on documents in a collection; with it, documents (records) can be differentiated from each one another. _id is automatically indexed. Lookups specifying { _id: <someval> } refer to the _id index as their guide. By default the _id field is of type ObjectID, one of MongoDB's BSON types.

How is _id generated in MongoDB?

By default, MongoDB generates a unique ObjectID identifier that is assigned to the _id field in a new document before writing that document to the database. In many cases the default unique identifiers assigned by MongoDB will meet application requirements.

Can we set _id in MongoDB?

_id field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.

What is meaning if _id in MongoDB?

What Is MongoDB ObjectID? As MongoDB documentation explains, "ObjectIds are small, likely unique, fast to generate, and ordered." The _id field is a 12-byte Field of BSON type made up of several 2-4 byte chains and is the unique identifier/naming convention MongoDB uses across all its content.


Video Answer


1 Answers

The Insert method automatically sets the property that is declared as the BSON ID of the model.

If declared as follows...

[BsonId] public ObjectId Id { get; set; } 

... then the Id field will contain the default (new, unique) BSON ID of the object after inserting the object into a collection:

coll.Insert(obj); // obj.Id is now the BSON ID of the object 
like image 138
Scott Hernandez Avatar answered Sep 22 '22 16:09

Scott Hernandez