本文介绍了插入MongoDB时如何防止_t和_v?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用字典.在 .insert()之后,有"_t"和"_v".这里有两篇文章谈到序列化首先转换为 JSON,然后转换为BSON .我正在使用MongoDB的驱动程序v2.4.3,

I'm utilizing Dictionary. After .insert() there are "_t" and "_v". Two posts here talked about serialization converting to JSON first then BSON. I'm using MongoDB's driver v2.4.3,

mCollection.InsertOne(x);
IMongoCollection<myDoc> mCollection = Db.GetCollection<myDoc>("whatever");

如果我将JSON转换为BSON,它会抱怨无法将BsonDocument转换为myDoc.切换到IMongoCollection<BsonDocument> mCollection = Db.GetCollection<BsonDocument>("whatever");仍会得到_t和_v.

If I do JSON-to-BSON, it complains about can't convert BsonDocument to myDoc. Switching to IMongoCollection<BsonDocument> mCollection = Db.GetCollection<BsonDocument>("whatever"); still get _t and _v.

如何避免_t和_v?

这是我的数据类型和利用率代码:

Here is my code of data type and utilization:

public class myObjForDictionary
    {
        //...
    }
    public class myDoc
    {
        // ... some other elements, then Dictionary
        public Dictionary<string, object> myDictionary { get; set; }
    }

    // to instantiate the
    class myClass
    {
        // define MongoDB connection, etc. 
        // instantiate myDoc and populate data
        var x = new myDoc
        {
            //...
            myDictionary = new Dictionary<string, object>
            {
                { "type", "something" },
                { "Vendor", new object[0] },
                { "obj1", //data for myObjForDictionary
                }
            };
        }

    }

推荐答案

您需要保存一些信息(_t),该信息关于反序列化器在反序列化对象时需要创建的对象,如果不这样做,它将不知道从BSON创建什么.

You'll need to save some information (_t) of what object the deserializer needs to create when deserializing the object, if not it won't know what to create from the BSON.

或者,您可以将Dictionary<string, object>更改为Dictionary<string, BsonDocument>并直接在代码中处理BsonDocument.这与在Newtonsoft.Json中使用JObject的方式非常相似.

Alternatively, you could change the Dictionary<string, object> to Dictionary<string, BsonDocument> and deal with the BsonDocuments directly within your code. This will be very similar to how you use JObject within Newtonsoft.Json.

这篇关于插入MongoDB时如何防止_t和_v?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 05:14