首页 > 代码库 > Insert Data with C# Driver

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

The MongoDB Manual

 

Insert Data with C# Driver