[英]using string for mongodb _id
I have a json document that I entered into my mongo db using the mongoimport command.我有一个 json 文档,我使用 mongoimport 命令将它输入到我的 mongo 数据库中。 I set it's _id to "MyDocId", looking at it in mongo, the _id is correctly set.
我将它的 _id 设置为“MyDocId”,在 mongo 中查看它,_id 设置正确。 in my C# code, I want to read this document using this _id:
在我的 C# 代码中,我想使用这个 _id 阅读这个文档:
ObjectId id = ObjectId.Parse("MyDocId");
I am getting an exception in the above code我在上面的代码中遇到异常
You may need to use a Bson attribute on your property like so.您可能需要像这样在您的属性上使用 Bson 属性。
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
There is quite a good explanation of these attributes in this answered question在这个回答的问题中对这些属性有很好的解释
ObjectId parse will only parse strings that have a valid format . ObjectId parse 将只解析具有有效格式的字符串。 In your case, if the document's
_id
is a string, you don't need to parse it as an ObjectId, just use the string value in your query.在您的情况下,如果文档的
_id
是字符串,则无需将其解析为 ObjectId,只需在查询中使用字符串值即可。
Since version 2.9 of MongoDB.Driver
you can also use built-in convention StringIdStoredAsObjectIdConvention从
MongoDB.Driver
2.9 版开始,您还可以使用内置约定StringIdStoredAsObjectIdConvention
var pack = new ConventionPack
{
new StringIdStoredAsObjectIdConvention()
};
ConventionRegistry.Register("Custom Convention", pack, t => true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.