简体   繁体   English

C#类到BSON往返

[英]C# class to BSON roundtrip

I am attempting to use MongoDB to store some classes that I habe in an application. 我试图使用MongoDB来存储我在应用程序中存在的某些类。

The code I use is 我使用的代码是

string json = JsonConvert.SerializeObject(item);
BsonDocument document = BsonDocument.Parse(json);
...
await collection.InsertOneAsync(document);

Which seems to work fine. 这似乎工作正常。 When I retrieve the documents from MongoDB I get a BsonDocument which has an "_id" attribute added. 当我从MongoDB中检索文档时,会得到一个BsonDocument,其中添加了“ _id”属性。

How do I get back to an instance of the original class (which does not have the _id attribute) 如何返回原始类的实例(不具有_id属性)

MongoDB automatically adds in the object ID (_id) attribute to serve as the primary key. MongoDB自动添加对象ID(_id)属性作为主键。 This happens the moment you do any sort of insertion into MongoDB (no matter if you import a JSON, BSON, CSV, or whatever) 在您向MongoDB中进行任何形式的插入时都会发生这种情况(无论您导入JSON,BSON,CSV还是其他方式)

http://docs.mongodb.org/manual/reference/object-id/ http://docs.mongodb.org/manual/reference/object-id/

If you want to get around this issue in your C# application, one option would be to export from MongoDB to CSV, and then use a tool to import the CSV into a JSON, while selectively avoiding the _id. 如果要在C#应用程序中解决此问题,一种选择是从MongoDB导出到CSV,然后使用一种工具将CSV导入JSON,同时有选择地避免使用_id。 This seems a bit complex unnecessarily though. 但是,这似乎有点复杂。

Perhaps you can just keep the _id attribute and make it an optional parameter in your original C# class? 也许您可以只保留_id属性并将其设置为原始C#类中的可选参数? Can you explain why the presence of the _id parameter an issue to begin with? 您能解释为什么_id参数存在是一个问题吗?

You can also remove the _id field from the BsonDocument after you have read it from the database: 从数据库中读取_id字段后,还可以从其删除BidDocument:

var document = collection.Find(new BsonDocument()).FirstAsync();
document.Remove("_id");

This only removes the _id from the BsonDocument in memory (the value of the document variable), not from the document stored in the database. 这只会从内存中的BsonDocument(文档变量的值)中删除_id,而不会从数据库中存储的文档中删除_id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM