官方驱动查询:
Query.All("name", "a", "b");//通过多个元素来匹配数组 Query.And(Query.EQ("name", "a"), Query.EQ("title", "t"));//同时满足多个条件 Query.EQ("name", "a");//等于 Query.Exists("type", true);//判断键值是否存在 Query.GT("value", 2);//大于> Query.GTE("value", 3);//大于等于>= Query.In("name", "a", "b");//包括指定的所有值,可以指定不同类型的条件和值 Query.LT("value", 9);//小于< Query.LTE("value", 8);//小于等于<= Query.Mod("value", 3, 1);//将查询值除以第一个给定值,若余数等于第二个给定值则返回该结果 Query.NE("name", "c");//不等于 Query.Nor(Array);//不包括数组中的值 Query.Not("name");//元素条件语句 Query.NotIn("name", "a", 2);//返回与数组中所有条件都不匹配的文档 Query.Or(Query.EQ("name", "a"), Query.EQ("title", "t"));//满足其中一个条件 Query.Size("name", 2);//给定键的长度 Query.Type("_id", BsonType.ObjectId );//给定键的类型 Query.Where(BsonJavaScript);//执行JavaScript Query.Matches("Title",str);//模糊查询 相当于sql中like -- str可包含正则表达式
其他参考如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MongoDB.Bson; using MongoDB.Driver; namespace mongodb { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // MongoDB连接串,以[mongodb: // ]开头。这里,我们连接的是本机的服务 //* string connectionString = "mongodb://localhost"; // 连接到一个MongoServer上 MongoServer server = MongoServer.Create(connectionString); // ------------------------------------------------------------------------- // 打开数据库testdb MongoDatabase db = server.GetDatabase("test"); // 获取集合employees MongoCollection collection = db.GetCollection("user"); // ------------------------------------------------------------------------- // 查询上面那个刚刚插进去的数据,就这格式了,看看QueryDocument的文档吧 var query = new QueryDocument(); //query.Add("name", "zs"); BsonDocument b = new BsonDocument(); //b.Add("$gt", 30); b.Add("$lt", 30); query.Add("age", b); MongoCursor cur = collection.FindAs<BsonDocument>(query); // 遍历结果 foreach (BsonDocument emp in cur) { // BsonValue有两种取值方式,下面两个都用了一个是AsXXX,一个是ToXXX var name = emp["name"].AsString;var age = 0.0; if (emp.Contains("age")) { age = emp["age"].AsDouble; } Console.WriteLine(" name:{0},age:{1}", name, age); } //*/ } } }
/*--------------------------------------------- * sql : SELECT * FROM table WHERE ConfigID > 5 AND ObjID = 1 *--------------------------------------------- */ QueryDocument query = new QueryDocument(); BsonDocument b = new BsonDocument(); b.Add("$gt", 5); query.Add("ConfigID", b); query.Add("ObjID", 1); MongoCursor<Person> m = mongoCollection.FindAs<Person>(query); /*--------------------------------------------- * sql : SELECT * FROM table WHERE ConfigID > 5 AND ConfigID < 10 *--------------------------------------------- */ QueryDocument query = new QueryDocument(); BsonDocument b = new BsonDocument(); b.Add("$gt", 5); b.Add("$lt", 10); query.Add("ConfigID", b); MongoCursor<Person> m = mongoCollection.FindAs<Person>(query);