Insert Data with C# Driver
Posted Chuck Lu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Insert Data with C# Driver相关的知识,希望对你有一定的参考价值。
https://docs.mongodb.com/getting-started/csharp/insert/
OverView
You can use the InsertOneAsync method and the InsertManyAsync method to add documents to acollection in MongoDB.
If you attempt to add documents to a collection that does not exist, MongoDB will create the collection for you.
Prerequisites
Follow the Connect to MongoDB step to connect to a running MongoDB instance and declare and define the variable _database to access the test database.
Include the following using statements.
using System;
using System.Threading.Tasks;
using MongoDB.Bson;
Insert a Document
Insert a document into a collection named restaurants.
The operation will create the collection if the collection does not currently exist.
private async void button1_Click(object sender, EventArgs e) { MongoClient = new MongoClient(); //根据名字获取数据库 MongoDatabase = MongoClient.GetDatabase("test"); var document = new BsonDocument { { "address", new BsonDocument { {"street", "2 Avenue"}, {"zipcode", "10075"}, {"building", "1480"}, {"coord", new BsonArray {73.9557413, 40.7720266}} } }, {"borough", "Manhattan"}, {"cuisine", "Italian"}, { "grades", new BsonArray { new BsonDocument { {"date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc)}, {"grade", "A"}, {"score", 11} }, new BsonDocument { {"date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc)}, {"grade", "B"}, {"score", 17} } } }, {"name", "Vella"}, {"restaurant_id", "41704620"} }; //根据名字获取collection var collection = MongoDatabase.GetCollection<BsonDocument>("restaurants"); await collection.InsertOneAsync(document); }
The method does not return a result
If the document passed to the InsertOneAsync method does not contain the _id field, the driver automatically adds the field to the document and sets the field’s value to a generated ObjectId
Additional Information
n the C# Driver documentation, see InsertOneAsync, InsertManyAsync and BsonDocument.
In the MongoDB Manual, see also the Insert Documents tutorial.
SEE ALSO
以上是关于Insert Data with C# Driver的主要内容,如果未能解决你的问题,请参考以下文章
SQL Insert into with select from multiple tables
C# - INSERT INTO 语句中的语法错误(System.Data.dll 中发生“System.Data.OleDb.OleDbException”类型的未处理异常)
Google Drive API 客户端(Python):files().insert() 的权限不足
Google Drive API 客户端(Python):files().insert() 的权限不足
[React Testing] Test Drive Assertions with Dates in React
Can not issue data manipulation statements with executeQuery()