1

I am using the .NET MongoDB driver to insert values into my collection in MongoDB .

I noticed when I insert an entity the objects get stored as simple columns like in the second document below where as when I used a BsonDocument to insert documents they get inserted as an object under the _v column in the first document below.

enter image description here

Can someone explain whats the difference between the two?

Also is it possible to insert the BsonDocument like in the second document via the .NET driver? In my case I have to build the document Dynamically since I dont have a concrete entity to insert with.

2
  • 1
    please provide a repo Commented Sep 20, 2021 at 14:18
  • 1
    Can you provide the code that you use for inserting documents in the collection? Commented Sep 30, 2021 at 7:14

2 Answers 2

2

The result you're seeing is related to dynamic handling. Mongo driver doesn't know which type you use and save this information in _t field. To fix it you just need to create collection based on BsonDocument directly like:

  var coll = db.GetCollection<BsonDocument>("coll");
  coll.InsertOne(new BsonDocument("name", "value"));

See this doc

Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer, I will upvote later. I was also able to db.GetCollection<dynamic>(...) and still insert a BsonDocument object without extra _t info, as described here and here
-1

So with the .NET driver:

  1. If I insert the bson object directly the document is inserted as an object with column "_v"

  2. If I insert the bson object after deserializing it using the BsonSerializer it can be inserted as simple columns in MongoDB.

             var collection = database.GetCollection<dynamic>(collectionName);
             var bson = new BsonDocument();
             ...
             // Fill bson object
             ...
             collection.InsertOne(bson); // Image 1 
             collection.InsertOne(BsonSerializer.Deserialize<dynamic>(bson)); // Image 2
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.