Mongodb提供了多種開發(fā)語言的驅(qū)動,java,python,c++,c# 等,這里選用c#驅(qū)動作為測試;
首先上mongo官網(wǎng)下載驅(qū)動。Ps:官方網(wǎng)站經(jīng)常連接不順利。
還不如直接在vs的nuget管理包中搜索mongoDB.driver.
需要引入的命名空間:
using MongoDB.Bson;using MongoDB.Driver;
Driver是驅(qū)動核心,Bson是和數(shù)據(jù)格式相關(guān)的;
定義一個mongo客戶端,一個mongodb,一個數(shù)據(jù)集合;
protected staticIMongoClient client;protected staticIMongoDatabase database;protected staticIMongoCollection<BsonDocument> collection;
連接上MongoDB
//定義連接client = new MongoClient("mongodb://127.0.0.1:27017");//獲取test數(shù)據(jù)庫database = client.GetDatabase("test"); //獲取test數(shù)據(jù)庫中的集合bioscollection = database.GetCollection<BsonDocument>("bios");
這里解釋說明下:首先你得讓mongod(mongo的服務(wù)端)運行起來,不然服務(wù)端都沒開,怎么連接呢;目前測試還沒有涉及到安全以及用戶權(quán)限數(shù)據(jù)庫管理這塊,所以這里的連接都是使用的默認不帶用戶登錄驗證;
需求注意的是,如果我們建立的是控制臺程序,那么這個連接必須寫地址必須帶端口,就像上面所寫;
如果是建立的一個MVC web,你僅僅是測試數(shù)據(jù)插入,在這種無安全驗證的方式下,你可以省去連接字符串。
如下圖;
接下來就是定義一個測試數(shù)據(jù):
var document =new BsonDocument { { "address" , newBsonDocument { { "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" } };
最后調(diào)用InsertOneAsync()
方法;
collection.InsertOneAsync(document);
最終插入結(jié)果:
這里使用shell來看數(shù)據(jù)的話就太不直觀了,這里使用的是比較常用的一個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(); } }}
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點
疑難解答