using MongoDB.Bson; ObjectId id = ObjectId.GenerateNewId(); Console.WriteLine(id); // Outputs a new ObjectId
using MongoDB.Driver; var collection = database.GetCollectionThis example demonstrates how to use GenerateNewId to generate a new ObjectId and set it as the _id field of a new document before inserting it into a MongoDB collection. The ObjectId.GenerateNewId method is part of the MongoDB.Driver core library and does not require any additional package installations.("myCollection"); var document = new BsonDocument { { "_id", ObjectId.GenerateNewId() }, { "name", "John Doe" }, { "age", 30 } }; collection.InsertOne(document);