1

I'm trying to inserting data to MongoDB using C#, JObject, and BSONDocument without defining any model (direct JSON). Maybe this is possible duplicate from How to remove _v and _t from mongo document and How to prevent _t and _v when inserting into MongoDB? , but I can't find my answer.

But there's _t and _v field. And the value that i put before, stored in _v field as an object.

Here's the code

var mongo = new MongoClient(new MongoUrl("mongodb://localhost"));
var db = "test";
var database = mongo.GetDatabase(db);
dynamic obj = new JObject();
obj["coy"] = "haha";
BsonDocument c = BsonDocument.Parse(obj.ToString());
database.GetCollection<dynamic>("test").InsertOne(c);

and the result

// 1
{
    "_id": ObjectId("5ca5ace48d93c485ce90bb43"),
    "_t": "MongoDB.Bson.BsonDocument, MongoDB.Bson",
    "_v": {
        "coy": "haha"
    }
}

Any ideas? Thank you.

Skipm3
  • 226
  • 2
  • 13
  • Is there some reason you can't define a model for this? I suspect the problem would simply disappear if you did. The `_t` and `_v` values (which I suspect stand for _type_ and _value_ respectively) are just the inner logic of the dynamic type being dumped straight into the database. – Greg Stanley Apr 04 '19 at 15:49
  • Because the user input is dynamic. And if I make a model for it, it'll going to be about 30+ model. – Skipm3 Apr 05 '19 at 01:47

1 Answers1

2

Use BsonDocument as the collection type:

database.GetCollection<BsonDocument>("test").InsertOne(c);
Greg Stanley
  • 328
  • 1
  • 3
  • 10