Docs 菜单
Docs 主页
/ / /
C#/.NET
/

插入文档

在此页面上

  • 例子
  • 预期结果
  • 更多信息
  • API 文档

您可以使用同步 InsertOne() 方法或异步 InsertOneAsync() 方法将单个文档插入集合中。

以下示例将文档插入 restaurants 集合。

选择 AsynchronousSynchronous 标签页,查看相应的代码。

Restaurant newRestaurant = new()
{
Name = "Mongo's Pizza",
RestaurantId = "12345",
Cuisine = "Pizza",
Address = new()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
await _restaurantsCollection.InsertOneAsync(newRestaurant);

有关 InsertOneAsync() 操作的完全可运行示例,请参阅异步插入一个示例

Restaurant newRestaurant = new()
{
Name = "Mongo's Pizza",
RestaurantId = "12345",
Cuisine = "Pizza",
Address = new()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
_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" : { } }] }

如需了解有关使用生成器的更多信息,请参阅生成器操作

后退

查找多个文档