[CSHARP-2019] IMongoCollection<BsonValue> causes InsertOne to fail to insert "_id" member Created: 20/Jul/17  Updated: 27/Oct/23  Resolved: 20/Jul/17

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: 2.4.4
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Max Barraclough [X] Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: Bug
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

.Net Framework 4.5.2 on Windows 10



 Description   

If I use IMongoCollection<BsonValue> rather than IMongoCollection<BsonDocument>, and use the InsertOne method to add a document which does not specify its own "_id" value, then InsertOne fails to insert the auto-generated "_id" member into the document object.

                MongoClient myClient = new MongoDB.Driver.MongoClient(ConnectionConf);
                var myDB = myClient.GetDatabase(DBName);
 
                bool avoidBug = false;
 
                if (avoidBug)
                {
                    IMongoCollection<BsonDocument> myCollectionGood = myDB.GetCollection<BsonDocument>(CollectionName);
                    // InsertOne modifies doc as expected: it adds an "_id" member
                    myCollectionGood.InsertOne(doc);
                }
                else
                {
                    IMongoCollection<BsonValue> myCollectionBad = myDB.GetCollection<BsonValue>(CollectionName);
                    // InsertOne fails to modify doc: it does not add the "_id" member
                    myCollectionBad.InsertOne(doc);
                }



 Comments   
Comment by Robert Stam [ 20/Jul/17 ]

The only thing that a collection can contain are documents, so the <T> in IMongoCollection<T> must be something that can be serialized as a document.

It is not possible to have an IMongoCollection<BsonValue>, because that would imply that you could insert a scalar type (such as integer or string) into a collection.

The only valid BsonValue subclass that can be inserted into a collection is a BsonDocument.

You should just use IMongoCollection<BsonDocument>.

Generated at Wed Feb 07 21:41:23 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.