1. 连接MONGODB数据库
#地址 IMongoClient mongoClient = new MongoClient("mongodb://127.0.0.1:27017"); #要操作的库 IMongoDatabase Database = mongoClient.GetDatabase("DataBaseName"); #要操作的表 IMongoCollection<Model> Table = Database.GetCollection<Model>("tablename");
2. 查询
查所有
Table.Find(new BsonDocument()).ToList();
查单个
Table.Find(new BsonDocument()).FirstOrDefault();
指定查询个数 LIMIT
Table.Find(new BsonDocument()).Limit(100);
指定排序方式 SORT
#升序 SortDefinition<Mode> sort = Builders<Mode>.Sort.Ascending(r => r.DeviceID); #降序 SortDefinition<Mode> sort = Builders<Mode>.Sort.Descending(r => r.AlarmNO); #使用 Table.Find(new BsonDocument()).Sort(sort).Limit(100).ToList();
指定跳过条数 SKIP
Table.Find(new BsonDocument()).Sort(sort).Skip(100).ToList();
限制器 FILTERDEFINITION
# 查 DeviceID = "ZTDZ03A01" FilterDefinition<Model> filter = Builders<Model>.Filter.Eq(r => r.DeviceID, "ZTDZ03A01"); # 查 DeviceID > "ZTDZ03A01" FilterDefinition<Model> filter = Builders<Model>.Filter.Gt(r => r.DeviceID, "ZTDZ03A01"); # 查 DeviceID < "ZTDZ03A01" FilterDefinition<Model> filter = Builders<Model>.Filter.Lt(r => r.DeviceID, "ZTDZ03A01"); # 条件查询 DeviceID = "ZTDZ03A01" FilterDefinition<Model> filter = Builders<Model>.Filter.Where(r => r.DeviceID == "ZTDZ03A01"); #使用 Table.Find(filter).FirstOrDefault();
3. 插入
# 单个插入 Table.InsertOne(Model); Table.InsertOneAsync(Model); # 多个插入 Table.InsertMany(List<Model>); Table.InsertManyAsync(List<Model>);
4. 删除
# 删除单个 Table.DeleteOne(new BsonDocument()); Table.DeleteOneAsync(new BsonDocument()); # 删除所有 Table.DeleteMany(new BsonDocument()); Table.DeleteManyAsync(new BsonDocument());
5. 修改
#修改单个 UpdateDefinition<Model> update = Builders<Model>.Update.Set("DeviceID", "2"); Table.UpdateOne(new BsonDocument(),update); #修改多个 UpdateDefinition<Model> update = Builders<Model>.Update.Set("DeviceID", "2"); Table.UpdateMany(new BsonDocument(),update);
UPDATEDEFINITION 使用示例
//将所有类的DeviceID修改为2,Yield修改为3 List<UpdateDefinition<Model>> list = new List<UpdateDefinition<Model>>(); UpdateDefinition<Model> update = Builders<Model>.Update.Set("DeviceID", "2"); list.Add(update); UpdateDefinition<Model> update1 = Builders<Model>.Update.Set("Yield", "3"); list.Add(update1); UpdateDefinition<Model> updates = Builders<Model>.Update.Combine(list);