如何从 mongo 文档中删除 _v 和 _t

Luk*_*101 6 c# mongodb

我到处搜索,没有任何解决方案。这是我插入数据的方式:

string value = db.StringGet("test");
string cleaned = value.Replace("u'", "'").Replace("\"", "");
var jsonDoc = Newtonsoft.Json.JsonConvert.SerializeObject(cleaned);
Dictionary<string, string> dict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonDoc);
values.Add(dict);

_collection.InsertMany(values.Select(x => x.ToBsonDocument()));
Run Code Online (Sandbox Code Playgroud)

这是数据在数据库中的外观

{ 
    "_id" : ObjectId("5aaabf7ac03af44892673031"), 
    "_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson", 
    "_v" : {
        "profile" : "myprofile", 
        "source" : "thesource", 
        "hostname" : "myhost", 
        "pgm" : "mypgm"
    }
}
Run Code Online (Sandbox Code Playgroud)

我不希望在 mongo 中像这样格式化数据。我的原因是因为我有几个客户端访问数据库。我宁愿将数据格式化如下:

{ 
    "_id" : ObjectId("5aaabf7ac03af44892673031"), 
    "profile" : "myprofile", 
    "source" : "thesource", 
    "hostname" : "myhost", 
    "pgm" : "mypgm"
}
Run Code Online (Sandbox Code Playgroud)

小智 1

在我们的团队中,我们通过序列化和反序列化对象来解决这个问题,使其成为 ExpandoObject。尝试这样的事情:

    JsonSerializer DynamicDataJsonSerializer;
    DynamicDataJsonSerializer = JsonSerializer.Create(JsonConverterSetup.GetTransparentSerializerSettings());

    MyClass dataToSaveToMogo;
    var dataToSaveToMogoAsDynamic = DynamicDataJsonSerializer.Deserialize<ExpandoObject>(DynamicDataJsonSerializer.Serialize(dataToSaveToMogo));
Run Code Online (Sandbox Code Playgroud)

然后保存 dataToSaveToMogoAsDynamic。

希望能帮助到你