作者:亦惜缘2 | 来源:互联网 | 2014-05-28 16:53
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingMongoDB.Bson;usingMongoDB.Driver;namespaceConsoleApplication1{classProgram{st
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
using MongoDB.Driver;
namespace ConsoleApplication1
{
class Program
{
static void
Main(string[] args)
{
//添加MongoDB.Bson.dll和MongoDB.Driver.dll的引用
// MongoDB连接串,以[mongodb://]开头。这里,我们连接的是本机的服务
//mongodb://[username:password@]hostname[:port][/[database][?options]]//MongoDB连接串的格式
string cOnnection= "mongodb://localhost";
MongoClient mOnClient= new
MongoClient(connection);
MongoServer server = monClient.GetServer();
MongoDatabase dataBase =
server.GetDatabase("lks");//这个名字是随便取的(有就获取,没有就会创建)
MongoCollection collection =
dataBase.GetCollection("users");//这个名字也是一样的(有就会获取,没有就会创建)
BsonDocument user = new BsonDocument();
//server.Connect();//这个方法是没有必要调用的(因为驱动会自动调用)
//普通插入
var o = new { Uid = 120, Name = "Andy", Password =
"123456" };
collection.Insert(o);
//对象插入
Person p = new Person { Uid = 121, Name = "Jack",
Password = "654321" };
collection.Insert(p);
//BsonDocument插入
BsonDocument bdoc = new BsonDocument();
bdoc.Add("Uid", 122);
bdoc.Add("Name", "Tom");
bdoc.Add("Password", "567890");
collection.Insert(bdoc);
Console.ReadLine();
}
}
class Person
{
public int
Uid;
public string
Name;
public string
Password;
}
}