版本:MongoDB.Driver v2.3.0.157
网上对这个驱动版本的代码相对很少,应该是这个驱动刚发布不久,我用这个驱动来实现mongodb的查询
一种方法是通过AsQueryable 用linq查询 另外一种方式是通过Find进行查询,当然,两种都可以支持lambda表达式
支持模糊查询和精确查询,支持排序,分页没做,其实,分页很简单,后面有扩展方法。
我写了15种调用方式,代码如下:
- using MongoDB.Bson;
- using MongoDB.Driver;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- namespace MongodbDemo
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- MongoHelper<Test> mongo = new MongoHelper<Test>("tab1");
- //通过linq查询全部
- IList<Test> model1 = mongo.QueryAllLinq();
- //通过find查询全部
- IList<Test> model2 = mongo.QueryAllFind();//QueryAllFind(null,sort) 排序
- IList<Test> model3 = mongo.QueryAllFindExp();//QueryAllFindExp(null,sort) 排序
- //linq条件查询和模糊查询
- IList<Test> model4 = mongo.QueryAllLinq(m => m.title == "码农网");
- IList<Test> model5 = mongo.QueryAllLinq(m => m.title.Contains("码农"));
- //find条件查询和模糊查询
- IList<Test> model6 = mongo.QueryAllFindExp(m => m.title == "码农网");
- IList<Test> model7 = mongo.QueryAllFindExp(m => m.title.Contains("码农"));
- IList<Test> model8 = mongo.QueryAllFind(Builders<Test>.Filter.Eq(x => x.title, "码农网"));
- //增加排序
- var sort = Builders<Test>.Sort.Descending(m => m.title);
- IList<Test> model9 = mongo.QueryAllFindExp(m => m.title == "码农网", sort);
- IList<Test> model10 = mongo.QueryAllFindExp(m => m.title.Contains("码农"), sort);
- IList<Test> model11 = mongo.QueryAllFind(Builders<Test>.Filter.Eq(x => x.title, "码农网"), sort);
- //单条查询
- Test model12 = mongo.QueryFindFirstOrDefault();
- Test model13 = mongo.QueryFindFirstOrDefault(Builders<Test>.Filter.Eq(x => x.title, "码农网"));
- Test model14 = mongo.QueryFindFirstOrDefault(Builders<Test>.Filter.Eq(x => x.title, "码农网"), sort);
- Test model15 = mongo.QueryLinqFirstOrDefault(m => m.title == "码农网");
- foreach(var item in model1)
- {
- Console.WriteLine(item.ToString());
- }
- MessageBox.Show("ok");
- }
- private void button2_Click(object sender, EventArgs e)
- {
-
- }
- }
- [Serializable]
- public class Test
- {
- public ObjectId _id { get; set; }
- public string title { get; set; }
- public string url { get; set; }
- public string descrip{过滤}tion { get; set; }
- public string by { get; set; }
- public object num { get; set; }
- /// <summary>
- /// 重写tostring
- /// </summary>
- /// <returns></returns>
- public override string ToString()
- {
- return string.Format("id:{0},标题:{1},链接:{2},详情:{3},作者:{4},num:{5}", _id.ToString(), title, url, descrip{过滤}tion, by, num);
- }
- }
- }
复制代码
最后,附上源代码:
|