Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove _v and _t from mongo document

Tags:

c#

mongodb

I have searched all over and no solution works. Here is how I am inserting data:

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()));

Here is how the data looks in the database

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

I dont want the data formatted like this in mongo. The reason my is because I have several clients accessing the db. I would rather have the data formatted like this:

{ 
    "_id" : ObjectId("5aaabf7ac03af44892673031"), 
    "profile" : "myprofile", 
    "source" : "thesource", 
    "hostname" : "myhost", 
    "pgm" : "mypgm"
}
like image 212
Luke101 Avatar asked Mar 15 '18 19:03

Luke101


1 Answers

In our team we solved it by serializing and deserializing the object, making it an ExpandoObject. Try something like this:

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

    MyClass dataToSaveToMogo;
    var dataToSaveToMogoAsDynamic = DynamicDataJsonSerializer.Deserialize<ExpandoObject>(DynamicDataJsonSerializer.Serialize(dataToSaveToMogo));

then save dataToSaveToMogoAsDynamic.

Hope it helps

like image 51
dns_b Avatar answered Oct 20 '22 02:10

dns_b