获取MongoDB中插入文档的_id? [英] 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);
问题是完成此操作后,我想将用户重定向到带有产品的页面.所以我需要重定向说/products/<ObjectID>
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>
但是,如果没有手动查询数据库并查找具有相同字段等的文档,我将无法立即获得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.
有没有更简单的方法? (此外,在这种情况下,doc
由于某种原因返回null)
Is there an easier way? (also, doc
in this instance returns null for some reason)
推荐答案
Insert
方法自动设置声明为模型的BSON ID的属性.
The Insert
method automatically sets the property that is declared as the BSON ID of the model.
如果声明如下...
[BsonId]
public ObjectId Id { get; set; }
...,然后Id
字段将包含将对象插入集合后的默认(新的,唯一的)BSON ID:
... 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
这篇关于获取MongoDB中插入文档的_id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!