We are using MongoDB C#.NET Driver to insert entry as below:
var JSON = "{ 'UserName': '" + "Roy" + "', 'PasswordHash' : '" + "123" + "' }";
var document = BsonSerializer.Deserialize<BsonDocument>(JSON);
await collection.InsertOneAsync(document);
In MongoDb, it goes with
_id:ObjectId("5e54f9ea045dba534831a1a2")
Which gives issues when retrieved and tried to convert into json. How can I set the _id from C# code itself?
The _id
is always generated on a client side - the driver does that behind the scenes when you run .Insert()
or .Save()
. You can do that manually by running:
document["_id"] = ObjectId.GenerateNewId().ToString();