using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MongoDB.Driver;
using MongoDB.Bson;
namespace MongoDBTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Init();
}
private void Init()
{
// MongoDB連接串,以[mongodb://]開頭這裏,我們連接的是本機的服務
string connectionString = "mongodb://localhost:27017";
// 連接到一個MongoServer上
MongoServer server = MongoServer.Create(connectionString);
// -------------------------------------------------------------------------
// 打開數據庫testdb
MongoDatabase db = server.GetDatabase("testdb");
// 獲取集合employees
MongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("employees");
// 創建一個employee
BsonDocument employee = new BsonDocument
{
{ "name", "Ernest Hemingway" },
{ "title", "For Whom the Bell Tolls" },
{ "sex", "man" }
};
//
collection.Insert(employee);
//一次插入多條
//MongoCollection<BsonDocument> books;
//BsonDocument[] batch = {
// new BsonDocument {
// { "author", "Kurt Vonnegut" },
// { "title", "Cat's Cradle" }
// },
// new BsonDocument {
// { "author", "Kurt Vonnegut" },
// { "title", "Slaughterhouse-Five" }
// }
//};
//books.InsertBatch(batch);
// 查詢上面那個剛剛插進去的數據
var query = new QueryDocument("sex", "man");
//保存
BsonDocument book = collection.FindOne(query);
if (book != null)
{
book["title"] = "Cat's Cradle";
collection.Save(book);
}
//修改
//MongoCollection<BsonDocument> books;
//var query = new QueryDocument {
// { "author", "Kurt Vonnegut" },
// { "title", "Cats Craddle" }
//};
// var update = new UpdateDocument {
// { "$set", new BsonDocument("title", "Cat's Cradle") }
//};
//BsonDocument updatedBook = books.Update(query, update);
// 遍歷結果
foreach (BsonDocument emp in collection.Find(query))
{
string str = string.Format("name:{0}\ttitle:{1}\tsex:{2}", emp["name"].AsString,
emp["title"].ToString(),emp["sex"].AsString);
// BsonValue有兩種取值方式,下面兩個都用了一個是AsXXX,一個是ToXXX()
MessageBox.Show(str);
}
}
}
}
---Mongodb文檔.