We know that MongoDB does not support byte (there is no byte defined in Bsontype), but the data structures in the actual production environment (especially the ancient time data structures) often contain byte data items.
It is not possible to save the original data structure at this time, it is common to create an additional wrapper structure (wrapper internally converts a byte to an int such as MongoDB recognizable type), and finally wrapper into MongoDB.
Undoubtedly, this approach is not elegant.
(The following method is implemented in C #, the MongoDB driver is version 2.0)
We want to enable MongoDB to automatically convert byte to int, so that all problems are solved by the edge.
To speak in code:
Class Byteserializer:ibsonserializer { PublicType ValueType {Get{return typeof(byte); } } Public Object Deserialize(Bsondeserializationcontext context, Bsondeserializationargs args) {varB = (byte) context. Reader.readint32 ();returnb } Public void Serialize(Bsonserializationcontext context, Bsonserializationargs args,Object value) {context. Writer.writeint32 ((int)(byte)value); } }
The code above constructs a serialization class for byte
We then "MyClass" the target structure in the global section.
BsonClassMap.RegisterClassMap<MyClass>(cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(c => c.Id)); cm.GetMemberMap<byte>(o => o.ByteItem).SetSerializer(new ByteSerializer()); });
After the completion of this section, the data structure can be readily uploaded to MongoDB.
Other similar cases, such as enum underlying as byte, etc.
Have fun!
Reference Links:
Http://stackoverflow.com/questions/19664394/mongodb-c-sharp-exception-cannot-deserialize-string-from-bsontype-int32
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
How to deposit a structure with a byte data item in MongoDB