我正在使用ToBsonDocument扩展方法MongoDB.Bson来转换这个字典:
var dictionary = new Dictionary<string, object> {{"person", new Dictionary<string, object> {{"name", "John"}}}};
var document = dictionary.ToBsonDocument();
Run Code Online (Sandbox Code Playgroud)
这是结果文件:
{ "person" :
{ "_t" : "System.Collections.Generic.Dictionary`2[System.String,System.Object]",
"_v" : { "name" : "John" } } }
Run Code Online (Sandbox Code Playgroud)
有没有办法摆脱这些_t/_v的东西?我希望生成的文档看起来像这样:
{ "person" : { "name" : "John" } }
Run Code Online (Sandbox Code Playgroud)
UPD:我在DictionaryGenericSerializer中找到了代码:
if (nominalType == typeof(object))
{
var actualType = value.GetType();
bsonWriter.WriteStartDocument();
bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType));
bsonWriter.WriteName("_v");
Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType
bsonWriter.WriteEndDocument();
return;
}
Run Code Online (Sandbox Code Playgroud)
因此,当值类型为时,似乎没有太多选项可用于此序列化程序object.
我有一个使用MongoDB的c#驱动程序将Upserts转换为MongoDB数据库的应用程序。调用Update函数时,无法指定要更新的类型,然后_t插入带有元素类型的字段。
这是我用来升级的代码:
collection.Update(
Query.EQ("key", item.Key),
Update.Replace(item),
UpdateFlags.Upsert
);
Run Code Online (Sandbox Code Playgroud)
结果如下:

进行初始插入时不会发生这种情况,因为我可以指定类型。
如何在不插入_t字段的情况下制作Upsert ?
[编辑]这是我用于插入的代码:
collection.InsertBatch(ItemType, items);
Run Code Online (Sandbox Code Playgroud)