插入文档
您可以使用同步 InsertOne()
方法或异步 InsertOneAsync()
方法将单个文档插入集合中。
例子
以下示例将文档插入 restaurants
集合。
选择 Asynchronous 或 Synchronous 标签页,查看相应的代码。
// Generates a new restaurant document Restaurant newRestaurant = new() { Name = "Mongo's Pizza", RestaurantId = "12345", Cuisine = "Pizza", Address = new() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; // Asynchronously inserts the new document into the restaurants collection await _restaurantsCollection.InsertOneAsync(newRestaurant);
有关 InsertOneAsync()
操作的完全可运行示例,请参阅 异步插入 1 示例。
// Generates a new restaurant document Restaurant newRestaurant = new() { Name = "Mongo's Pizza", RestaurantId = "12345", Cuisine = "Pizza", Address = new() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; // Inserts the new document into the restaurants collection _restaurantsCollection.InsertOne(newRestaurant);
有关 InsertOne()
操作的完全可运行示例,请参阅同步插入一个示例。
预期结果
运行上述任一完整示例后, InsertOne()
方法会插入文档,而 Find()方法则会返回新插入的文档。 输出类似于以下内容:
Inserting a document... Document Inserted: { "_id" : ObjectId("..."), "name" : "Mongo's Pizza", "restaurant_id" : "12345", "cuisine" : "Pizza", "address" : { "_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson", "_v" : { "street" : "Pizza St", "zipcode" : "10003" } }, "borough" : "Manhattan", "grades" : [{ "_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson", "_v" : { } }] }
更多信息
如需了解有关使用生成器的更多信息,请参阅生成器操作。