先在NuGet中下载并安装驱动mongocsharpdriver,和客户端包MongoDB.Driver
代码如下
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
namespace TestMongoDB
{
[Serializable]
class Customer
{
public int id { set; get; }
public string name { set; get; }
public int age { set; get; }
}
class Program
{
public static void Main()
{
MongoClient client;
MongoServer server;
client = new MongoClient("mongodb://admin:Abc12345@localhost:27017/admin");
if (client != null)
{
Console.WriteLine("MongoDB connect success.");
server = client.GetServer();
MongoDatabase mdb = server.GetDatabase("foo");
MongoCollection<BsonDocument> collection = mdb.GetCollection("bar");
// Select operation
var records = collection.FindAll();
foreach (BsonDocument record in records)
{
Console.WriteLine(record);
}
// Insert operation
Customer customer = new Customer
{
id = 8,
name = "zahngsan",
age = 28
};
collection.Insert<Customer>(customer);
// Update operation
IMongoQuery iq4u = Query.EQ("name", "zhangsan_1");
IMongoUpdate iu = Update.Set("name", "zhangsan").Set("age", 98);
collection.Update(iq4u, iu, UpdateFlags.Multi);
// Delete operation
IMongoQuery iq4d = Query.EQ("name", "zhangsan_2");
collection.Remove(iq4d);
// Select as Object
/*MongoCollection<Customer> collection2 = mdb.GetCollection<Customer>("bar");
var customer1 = collection2.FindOne();
var customer2 = collection2.FindOneAs<Customer>();
foreach (BsonDocument record in records)
{
var customer3 = BsonSerializer.Deserialize<Customer>(record);
}*/
}
else
{
Console.WriteLine("MongoDB connect fail.");
}
}
}
}