Search code examples
c#mongodbbson

mongodb c# driver set _id of bson document


When creating a bson document with a custom id like in the following example, the _id is not 123, it will be auto generated

var balls = dbContext.Database.GetCollection<BsonDocument>("Balls");
var ballDoc = new BsonDocument
                {
                    {"_id", BsonObjectId.Parse("123")},
                    {"Name", ".."},
                };

 await balls.InsertOneAsync(ballDoc).ConfigureAwait(false);

When doing that:

var balls = dbContext.Database.GetCollection<Balls>("Balls");
var ball = new Ball
                {
                  Id = ...
                };

 await balls.InsertOneAsync(ball).ConfigureAwait(false);

The id is 123. Why? And how can I set an _id when using bson docs?


Solution

  • 123 is working fine the problem comes ONLY when setting the _id of the bson object to 000000000000000000000000. Everything else like 000000000000000000000001 works.
    But setting the _id of a typed object to 000000000000000000000000 works.... I need to live with it.