C# 查询MongoDB数据
更新时间:2022-12-21 09:23
实体类
public class User
{
public MongoDB.Bson.ObjectId Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
查询所有数据和总个数
public void Read()
{ //帐号 lqwvje 密码 123456
MongoClient client = new MongoClient("mongodb://lqwvje:123456@192.168.1.242:27017");
//获取database
IMongoDatabase mydb = client.GetDatabase("myDB");
//获取collection
IMongoCollection<User> collection = mydb.GetCollection<User>("user");
FilterDefinitionBuilder<User> builderFilter = Builders<User>.Filter;
//查询所有数据
List<User> result = collection.Find(builderFilter.Empty).ToList();
//查询总个数
var count = collection.Find(builderFilter.Empty).CountDocuments();
}
条件查询
按条件查询 Name="张三"
public void Read()
{
MongoClient client = new MongoClient("mongodb://lqwvje:123456@192.168.1.242:27017");
//获取database
IMongoDatabase mydb = client.GetDatabase("myDB");
//获取collection
IMongoCollection<User> collection = mydb.GetCollection<User>("user");
FilterDefinition<User> builderFilter = Builders<User>.Filter.Eq(u => u.Name, "张三");
//查询Name = 张三
List<User> result = collection.Find(builderFilter).ToList();
}
C#驱动MongoDB官方中查询条件Query用法
- 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可包含正则表达式
排序分页查询
public void Read()
{
MongoClient client = new MongoClient("mongodb://lqwvje:123456@192.168.1.242:27017");
//获取database
IMongoDatabase mydb = client.GetDatabase("myDB");
//获取collection
IMongoCollection<User> collection = mydb.GetCollection<User>("user");
FilterDefinitionBuilder<User> builderFilter = Builders<User>.Filter;
//分页 排序查询 SortBy升序 SortByDescending 降序
List<User> result = collection.Find(builderFilter.Empty).SortByDescending(u=>u.Id).Skip(0).Limit(10).ToList();
}