using System;
using System.Configuration;
using System.Linq;
using MongoDB;
using MongoDB.Configuration;
using MongoDB.Linq;
namespace Simple
{
///
/// Illustrates some simple operations on the database.
/// Creating a database connection.
/// Remove some documents.
/// Insert some documents
/// Find one document
/// Find several documents and iterate through them.
///
internal class MainClass
{
private IMongoCollection categories;
private Mongo mongo;
private IMongoDatabase simple;
private class MyClass
{
public string Name { get; set; }
public int Corners { get; set; }
}
private class SubClass : MyClass
{
public double Ratio { get; set; }
}
public static void Main(string[] args)
{
#region 以下为被屏蔽源码部分,我们先从SetUp方法开始
//var config = new MongoConfigurationBuilder();
//// COMMENT OUT FROM HERE
//config.Mapping(mapping =>
//{
// mapping.DefaultProfile(profile =>
// {
// profile.SubClassesAre(t => t.IsSubclassOf(typeof(MyClass)));
// });
// mapping.Map();
// mapping.Map();
//});
//// TO HERE
//config.ConnectionString("Server=127.0.0.1");
//using (Mongo mongo = new Mongo(config.BuildConfiguration()))
//{
// mongo.Connect();
// try
// {
// var db = mongo.GetDatabase("TestDb");
// var collection = db.GetCollection();
// MyClass square = new MyClass()
// {
// Corners = 4,
// Name = "Square"
// };
// MyClass circle = new MyClass()
// {
// Corners = 0,
// Name = "Circle"
// };
// SubClass sub = new SubClass()
// {
// Name = "SubClass",
// Corners = 6,
// Ratio = 3.43
// };
// collection.Save(square);
// collection.Save(circle);
// collection.Save(sub);
// var superclass = (from item in db.GetCollection("MyClass").Linq()
// where item.Corners > 1
// select item.Corners).ToList();
// var subclass = (from item in db.GetCollection("MyClass").Linq()
// where item.Ratio > 1
// select item.Corners).ToList();
// Console.WriteLine("Count by LINQ on typed collection: {0}", collection.Linq().Count(x => x.Corners > 1));
// Console.WriteLine("Count by LINQ on typed collection2: {0}", db.GetCollection().Linq().Count(x => x.Corners > 1));
// //Console.WriteLine("Count by LINQ on typed collection3: {0}", db.GetCollection().Count(new { Corners = Op.GreaterThan(1) }));
// Console.WriteLine("Count on typed collection: {0}", collection.Count(new { Corners = Op.GreaterThan(1) }));
// var coll = db.GetCollection("MyClass");
// var count = coll.Count(new Document("Corners", Op.GreaterThan(1)));
// Console.WriteLine("Count: {0}", count);
// Console.ReadKey();
// }
// finally
// {
// mongo.Disconnect();
// }
//}
#endregion
var main = new MainClass();
main.Setup();
main.Run();
Console.ReadLine();
}
///
/// Setup the collection and insert some data into it.
///
public void Setup()
{
//从配置文件读取连接字符串 IP+端口
var connstr = ConfigurationManager.AppSettings["simple"];
if(String.IsNullOrEmpty(connstr))
throw new ArgumentNullException("Connection string not found.");
//创建Mongo数据服务及连接
mongo = new Mongo(connstr);
mongo.Connect();
//获取数据库实例(如果该实例不存,就会自动创建simple实例)
simple = mongo["simple"];
//获取表名(如果该表名不存在,就会自动创建categories表名)
categories = simple.GetCollection("categories");
//添加记录前清除所有记录
Clean();
var names = new[] {"Bluez", "Jazz", "Classical", "Rock", "Oldies", "Heavy Metal"};
//循环插入记录 doucment会自动生成键值_id,id的编码体现了数据的插入顺序
foreach(var name in names)
categories.Insert(new Document {{"name", name}});
}
public void Clean()
{
//删除document name 为Jazz的记录
categories.Remove(new Document {{"name", "Jazz"}}); //remove documents with the name Jazz.
//删除所有记录集
categories.Remove(new Document()); //remove everything from the categories collection.
}
public void Run()
{
//查找单条记录 参数类型为Document
var category = categories.FindOne(new Document {{"name", "Bluez"}});
Console.WriteLine("The id findOne" + category["_id"]);
//更新1 用键值ID读取对象,并更新字段值,保存
var selector = new Document {{"_id", category["_id"]}};
category["name"] = "Bluess";
//The following will do the same thing.
categories.Save(category);
Console.WriteLine("Category after one update " + categories.FindOne(selector));
//更新2 Update参数1去更新参数2并保存
category["name"] = "Blues";
categories.Update(category, selector);
Console.WriteLine("Category after two updates " + categories.FindOne(selector));
//Find it by _id that has been converted to a string now.
var id = (category["_id"]).ToString();
//注意: 这里id.ToString()与id.ToOid() (为什么类扩展这个方法,我也没明白,是不是id!=24 位会出现转义字符要替换掉)
Console.WriteLine(string.Format("Found by string id[{0}] converted back to Oid[{1}]",id.ToString(),id.ToOid()));
Console.WriteLine(categories.FindOne(new Document {{"_id", id.ToOid()}}));
//Find(new Document()) is equivalent to FindAll();
//Specifying the cursor in a using block will close it on the server if we decide not
//to iterate through the whole thing.
Console.WriteLine("输出所有对象.........");
using(var all = categories.Find(new Document()))
{
foreach(var doc in all.Documents)
Console.WriteLine(doc.ToString());
}
mongo.Disconnect();
}
}
}
//类扩展ToOid方法到string中
public static class OidExtensions
{
public static Oid ToOid(this string str)
{
if(str.Length == 24)
return new Oid(str);
return new Oid(str.Replace("\"", ""));
}
} 以上为MongoDB的数据库连接及CRUD操作(Document方式),我们来测试一下,数据库实例,表,记录是否创建成功了呢?
打开上一章提到的Bin文件夹下的Mongo.exe程序 按图示输入命令查看
入门Demo就演示到这里了,有点简单,我也在是一边学习一边分享。Demo就不提供下载了,都在samus里面,只是我这边加了注释。