帮助中心/最新通知

质量为本、客户为根、勇于拼搏、务实创新

< 返回文章列表

【服务器相关】mongodb使用c#驱动数据插入demo

发表时间:2025-06-16 03:46:00 小编:主机乐-Yutio

Mongodb提供了多种开发语言的驱动,java,python,c++,c# 等,这里选用c#驱动作为测试;

首先上mongo官网下载驱动。Ps:官方网站经常连接不顺利。

还不如直接在vs的nuget管理包中搜索mongoDB.driver.

需要引入的命名空间:

接下来就是定义一个测试数据:

这里使用shell来看数据的话就太不直观了,这里使用的是比较常用的一个mongodb可视化管理工具Robomongo 

附上代码:


using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using MongoDB.Bson;using MongoDB.Driver;namespace mongodbInsert{class Program{protected static IMongoClient client;protected static IMongoDatabase database;protected static IMongoCollection<BsonDocument> collection; static void Main(string[] args){ client = new MongoClient("mongodb://127.0.0.1:27017"); database = client.GetDatabase("test"); collection = database.GetCollection<BsonDocument>("bios"); for (int i = 0; i < 14; i++) { 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.InsertOneAsync(document); } Console.WriteLine(); Console.ReadLine();}}}

总结

本篇文章到此结束,如果您有相关技术方面疑问可以联系我们技术人员远程解决,感谢大家支持本站!


联系我们
返回顶部