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文档.