对mongodb _id使用字符串 [英] using string for mongodb _id

查看:516
本文介绍了对mongodb _id使用字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用mongoimport命令输入到mongo数据库中的json文档. 我将它的_id设置为"MyDocId",在mongo中查看它,正确设置了_id. 在我的C#代码中,我想使用此_id阅读此文档:

ObjectId id = ObjectId.Parse("MyDocId");

上面的代码中出现异常

解决方案

您可能需要像这样在属性上使用Bson属性.

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }

在回答的问题中对这些属性有很好的解释

BsonId与BsonRepresentation

I have a json document that I entered into my mongo db using the mongoimport command. I set it's _id to "MyDocId", looking at it in mongo, the _id is correctly set. in my C# code, I want to read this document using this _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.

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }

There is quite a good explanation of these attributes in this answered question

BsonId vs BsonRepresentation

这篇关于对mongodb _id使用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆