NoSQL簡介
NoSQL相關的技術最近越來越受歡迎,Mongo本身就是基于NoSQL實現的。關于NoSQL你需要了解
- 什么是NoSQL
- NoSQL和傳統的關系型數據庫有什么區別
- NoSQL的優缺點
這幾個問題下面的文章有所介紹:
http://www.runoob.com/mongodb/nosql.html
http://www.infoq.com/cn/news/2011/01/nosql-why/
MongoDB
MongoDB 是由C++語言編寫的,是一個基于分布式文件存儲的開源數據庫系統。在高負載的情況下,添加更多的節點,可以保證服務器性能。MongoDB 旨在為WEB應用提供可擴展的高性能數據存儲解決方案。MongoDB 將數據存儲為一個文檔,數據結構由鍵值(key=>value)對組成。MongoDB 文檔類似于 JSON 對象。字段值可以包含其他文檔,數組及文檔數組。
更詳細的介紹可以參見:
http://www.runoob.com/mongodb/mongodb-intro.html
MongoDB安裝
去http://www.mongodb.org/downloads 地址下載并安裝MongoDB。
根據你的機器選擇相應的安裝包,32位系統上MongoDB數據庫最大為2G。
安裝結束后首先創建默認的數據庫存儲地址c:\data\db
通過命令行mongod.exe --dbpath c:\data\db來把mongodb和存儲路徑關聯起來,命令行顯示如下:
表示關聯成功,并且在27017端口上監聽連接。
MongoDB后臺管理Shell
在安裝路徑下執行mongo.exe文件會執行MongoDB Shell,是一個自帶的交互式的JavaScript Shell,用來對MongoDB進行操作和管理的交互式環境。
Shell中輸入help顯示幫助命令
數據庫創建刪除
- Shell中輸入 use tutorial來嘗試連接名為tutorial的數據庫,如果數據庫不存在則創建。
- 輸入db.dropdatabase()來刪除當前數據庫。
- 輸入show dbs顯示數據庫信息。
創建刪除表信息
- db.websites.insert({title:'www.baidu.com',url:'www.baidu.com'}) 來在websites表中插入一條記錄
- db.websites.find()查詢
C#操作MongoDB
首先下載.NET版本的MongoDB Driver,嘗試在Nuget找一下吧:
下載并安裝。
找到了API我們就可以進行增刪改查了,下面的Demo Code展示了基本的數據庫操作。
using System; using System.Xml.Linq; using MongoDB.Bson; using MongoDB.Driver; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace WikiExampleConsole { class Program { static void Main(string[] args) { Console.WriteLine("Connect..."); MongoConnectionStringBuilder builder = new MongoConnectionStringBuilder(); builder.Server = new MongoServerAddress("localhost", 27017); builder.DatabaseName = "tutorial"; MongoServer mongo = MongoServer.Create(builder); mongo.Connect(); Console.WriteLine("Connected"); Console.WriteLine(); var db = mongo.GetDatabase("tutorial"); using (mongo.RequestStart(db)) { var collection = db.GetCollection<BsonDocument>("books"); BsonDocument book = new BsonDocument() .Add("_id", BsonValue.Create(BsonType.ObjectId)) .Add("author", "Ernest Hemingway") .Add("title", "For Whom the Bell Tolls"); collection.Insert(book); var query = new QueryDocument("author", "Ernest Hemingway"); foreach (BsonDocument item in collection.Find(query)) { string json = item.ToJson(); Console.WriteLine(json); Console.WriteLine(); JToken token = JToken.Parse(json); token.SelectToken("title").Replace("some other title"); Console.WriteLine("Author: {0}, Title: {1}", token.SelectToken("author"), token.SelectToken("title")); Console.WriteLine(); XNode node = JsonConvert.DeserializeXNode(json, "documents"); Console.WriteLine("Node:"); Console.WriteLine(node); Console.WriteLine(); BsonElement author = item.GetElement("author"); BsonElement title = item.GetElement("title"); foreach (BsonElement element in item.Elements) { Console.WriteLine("Name: {0}, Value: {1}", element.Name, element.Value); } Console.WriteLine(); Console.WriteLine("Author: {0}, Title: {1}", author.Value, title.Value); } } Console.WriteLine(); Console.Read(); mongo.Disconnect(); } } }
相關代碼托管在了https://github.com/cuicheng11165/Mongo-Demo上。
文章列表