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 InsertOneAsyncInsertManyAsync and BsonDocument.

In the MongoDB Manual, see also the Insert Documents tutorial.

SEE ALSO

The MongoDB Manual

时间: 2025-01-22 04:48:25

Insert Data with C# Driver的相关文章

Instance Two: Insert Data to Mysql database

#!/usr/bin/env python #--*-- coding:utf-8 --*-- __author__ = 'Kevin' import MySQLdb as mdb import sys con = mdb.connect('localhost','root','redhat','test') try: with con: cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS Writers(Id INT PRIMA

简单的sqlserver批量插入数据easy batch insert data in sqlserver

DECLARE @pid INT,@name NVARCHAR(50),@level INT,@i INT,@column2 INT SET @pid=0 SET @name ='first' SET @level =5 SET @column2=0 SET @i=0 WHILE @i<30 --30为你要执行插入的次数 BEGIN INSERT INTO table_name ( pid, name,level, column2) VALUES ( @pid, @name,@level,@co

[李景山php]thinkphp核心源码注释|Driver.class.php

<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2014 http://thinkphp.cn A

Solution for sending Whatsapp via sqlite &quot;INSERT INTO&quot;

I use something similar but thought I'd mention this 'bug' that can happen:when you INSERT '%wa_message' into 'data', bear in mind your typed message will replace %wa_message.if that typed message contains an apostrophe, your message won't send.why?t

用直接路径(direct-path)insert提升性能的两种方法

1.传统串行insert方式 常见的insert方式有两种: (1)      insert into table_name values(....) (2)      insert into target_table select* from source_table 上面这两种常规的插入式,默认都是在串行方式下的插入,会将insert的数据写入buffer_cache,插入前检查表中是否有block中存有空闲空间可以追加插入,并写入redo log和数据的undo. 2.直接路径(direc

Data Types

原地址: Home / Database / Oracle Database Online Documentation 11g Release 2 (11.2) / Database Administration Data Types Each value manipulated by Oracle Database has a data type. The data type of a value associates a fixed set of properties with the va

UESTC_秋实大哥与战争 2015 UESTC Training for Data Structures&lt;Problem D&gt;

D - 秋实大哥与战争 Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Submit Status 男儿何不带吴钩,收取关山五十州. 征战天下是秋实大哥一生的梦想,所以今天他又在练习一个对战游戏. 秋实大哥命令所有士兵从左到右排成了一行来抵挡敌人的攻击. 敌方每一次会攻击一个士兵,这个士兵就会阵亡,整个阵列就会从这个位置断开:同时有的时候已阵亡的士兵会受人赢气息感染而复活. 秋

初识NoSQL 快速认识NoSQL数据库 分析Analytics For Hackers: How To Think About Event Data

做了一年的大一年度项目了,对于关系型数据库结构还是有些了解了,有的时候还是觉得这种二维表不是很顺手.在看过一篇文章之后,对NoSQL有了初步的了解,(https://keen.io/blog/53958349217/analytics-for-hackers-how-to-think-about-event-data).这边文章写的很好,确实写出来了在实际情况下NoSQL的“用武之地”,而且用了MineCraft作分析,但是也许不够全面.比如文章中只是提到了,entity数据用关系型怎么存,ev

[转]Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10)

本文转自:http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10) By