本文地址:http://www.cnblogs.com/vnii/archive/2012/08/23/2652891.html
1.C#下对MongoDB中的数据分组Group
IMongoQuery query = null; query = Query.And( Query.EQ("CityCode", "hangzhou"), Query.EQ("LT_IsBDT", 1), Query.EQ("LT_Checked", 1) ); Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary["num"] = 0; //IMongoGroupBy groupBy = null; //groupBy = GroupBy.Keys("LTT_ID"); GroupByBuilder groupByBuilder = new GroupByBuilder(new string[] { "LTT_ID", "LTT_TypeName", "LTT_ParentID" }); var tSmall = _mongoCollection.Group(query, groupByBuilder, BsonDocument.Create(dictionary), BsonJavaScript.Create("function(doc,prev){prev.num++;}"), BsonJavaScript.Create("function(doc){ doc.count=doc.num;delete doc.num; }")).ToList();
2.C#操作MongoDB的部分代码示例
MongoServer _mongoServer = MongoServer.Create("mongodb://192.168.90.245:10008/?safe=true"); //连接数据库 MongoDatabase _mongoDatabase = _mongoServer.GetDatabase("MYDB"); //选择数据库名 MongoCollection MongoCt = _mongoDatabase.GetCollection("MyCollection"); //选择集合,相当于表 //获取数据 public List<InfoModel> GetTopicListByType(string sKeyWord,int iPageSize,int iCurrPageIndex) { IMongoQuery query = null; query = Query.And( Query.EQ("LT_IsBDT", 1), Query.EQ("LT_Checked", 1), Query.Or(Query.EQ("LT_Status", 0), Query.EQ("LT_Status", 1)), Query.GTE("LT_CreateDate", DateTime.Now), Query.Matches("LT_Title", BsonRegularExpression.Create("/.*" + sKeyWord + ".*/")) ); SortByDocument sort = new SortByDocument { { "LT_CreateDate", -1 } }; return MongoCt.FindAs<InfoModel>(query).SetLimit(iPageSize).SetSkip(iPageSize * iCurrPageIndex).SetSortOrder(sort).ToList(); } //更新+1 public bool IncViewCount(int iLtId, int iInc) { IMongoQuery query; query = Query.And( Query.EQ("LT_ID", iLtId) ); UpdateBuilder update = new UpdateBuilder(); SafeModeResult r = MongoCt.Update(query, update.Inc("LT_ViewCount", iInc)); return r != null && r.Ok; } //插入数据 public bool InsertBatch<T>(IEnumerable<T> document) { List<SafeModeResult> result = (List<SafeModeResult>) this.MongoCt.InsertBatch<T>(document); return result != null && result[0] != null && result[0].Ok; } //根据ID删除数据 public bool RemoveBatchById(List<int> list) { IMongoQuery query = null; query = Query.And( Query.In("IA_ID",BsonArray.Create(list)) ); SafeModeResult result = this.MongoCt.Remove(query); return result != null && result.Ok; } //根据ID更新数据 public bool UpdateSingleByLtid(InfoModel model) { IMongoQuery query; query = Query.And( Query.EQ("IA_ID", model.IA_ID) ); BsonDocument bsonDocument = model.ToBsonDocument<InfoModel>(); bsonDocument.Remove("_id"); bsonDocument.Remove("IA_ID"); var update = new UpdateDocument { {"$set", bsonDocument} }; SafeModeResult result = this.MongoCt.Update(query, update); return result != null && result.Ok; } // 删除所有数据 public bool RemoveAll() { SafeModeResult r = this.MongoCt.Remove(null); return r != null && r.Ok; } // 创建索引 public bool CreateIndex1() { SafeModeResult r = this.MongoCt.CreateIndex( new IndexKeysBuilder().Ascending("IA_CityCode","IT_Key").Descending("IA_CreateDate") ); return r != null && r.Ok; } // 获取表索引 public GetIndexesResult GetIndex() { return this.MongoCt.GetIndexes(); } // 删除表索引 public bool DropIndex() { return this.MongoCt.DropAllIndexes().Ok; }
3.命令行下语法
db.collection.update( criteria, objNew, upsert, multi ) criteria : update的查询条件,类似sql update查询内where后面的 objNew : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的 upsert : 这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。 multi : mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。 //用法:{ $inc : { field : value } } //意思对一个数字字段field增加value, 如SQL-“update test0 set count=count+1 where _id=15” db.test0.update( { "_id" : 15 } , { $inc : { "count" : 1 } } ); //用法:{ $unset : { field : 1} } //顾名思义,就是删除字段了,删除某条件下的文档中的某个列,如: db.test0.update( { "_id" : 15 } , { $unset : { "Age":1 } } ); //添加字段赋值 db.test0.find().forEach( function(item){ db.test0.update({},{"$set":{"CreateDate":item.UpdateDate}},false,true) } ) db.test0.find({CityCode:"hz","CreateDate":{$exists:false}}).forEach( function(item){ db.test0.update({CityCode:"hz","CreateDate":{$exists:false}},{"$set":{"CreateDate":item.UpdateDate}},false,true) } ) //查询指定字段 db.test0.find({},{"CreateDate":1,_id:0}) //查找不存在字段FName的记录 db.test0.find({CityCode:"hz","FName":{$exists:false}}) //创建索引 db.test0.ensureIndex({"CityCode":1,"LT_ID":-1},{"name":"test0ByLtId"}) //删除索引 db.runCommand({deleteIndexes: "表名", index: "索引名"}) //删除指定索引 db.test0.dropIndexes() //删除所有索引 //查看索引 db.test0.getIndexes() //列重命名 db.test0.update({},{$rename:{"BigTypeName":"ParentTypeName"}},false,true) db.test0.remove({}); // 删除things中的所有数据 db.test0.remove({n:1}); // 删除things中n=1的所有数据 类似delete where n = 1 // 链接字符串 Servers=IP:27017;ConnectTimeout=30000;ConnectionLifetime=300000;MinimumPoolSize=8;MaximumPoolSize=256;Pooled=true