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)
_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.
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.
_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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With