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.
向名为restaurants的Collection插入一条Document: 等同于关系型数据库中,向表名为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
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-03-01 Unicode and .NET
2016-03-01 tracert 路由跟踪程序