相关疑难解决方法(0)

字典<string,object> -to-BsonDocument转换省略_t字段

我正在使用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.

c# dictionary mongodb bson

8
推荐指数
2
解决办法
1万
查看次数

在向上插入MongoDB时,如何防止出现“ _t”字段?

我有一个使用MongoDB的c#驱动程序将Upserts转换为MongoDB数据库的应用程序。调用Update函数时,无法指定要更新的类型,然后_t插入带有元素类型的字段。

这是我用来升级的代码:

collection.Update(
    Query.EQ("key", item.Key),
    Update.Replace(item),
    UpdateFlags.Upsert
);
Run Code Online (Sandbox Code Playgroud)

结果如下:

mongodb截屏

进行初始插入时不会发生这种情况,因为我可以指定类型。

如何在不插入_t字段的情况下制作Upsert ?

[编辑]这是我用于插入的代码:

collection.InsertBatch(ItemType, items);
Run Code Online (Sandbox Code Playgroud)

c# mongodb

5
推荐指数
1
解决办法
1081
查看次数

标签 统计

c# ×2

mongodb ×2

bson ×1

dictionary ×1