简体   繁体   中英

C# class to BSON roundtrip

I am attempting to use MongoDB to store some classes that I habe in an application.

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.

How do I get back to an instance of the original class (which does not have the _id attribute)

MongoDB automatically adds in the object ID (_id) attribute to serve as the primary key. This happens the moment you do any sort of insertion into MongoDB (no matter if you import a JSON, BSON, CSV, or whatever)

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. 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? Can you explain why the presence of the _id parameter an issue to begin with?

You can also remove the _id field from the BsonDocument after you have read it from the database:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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