插入文档
您可以使用同步的InsertOne()
方法或异步的 InsertOneAsync()
方法将单个文档插入到集合中。
示例
以下示例将文档插入到 restaurants
集合中。
选择异步 或 同步 选项卡以查看相应的代码。
// 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()
操作的完整可运行示例,请参阅异步插入一个示例.
// 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" : { } }] }
更多信息
有关使用构建器的更多信息,请参阅 使用构建器进行操作。