/// <summary> /// 删除操作 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Delete(Expression <Func <T, bool> > func) { using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); //这个地方要注意,一定要加上T参数,否则会当作object类型处理 //导致删除失败 collection.Remove <T>(func); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } }
public bool DeleteEnduser(string iSimCardNo, out string msg) { Mongo mongo = new Mongo(connectionString); MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; try { mongo.Connect(); //List<EndUser> userList = new List<EndUser>(); IEnumerable<Document> doc = mongoCollection.Find(new Document { { "SimCardNo", iSimCardNo } }).Documents; mongoCollection.Remove(new Document { { "SimCardNo", iSimCardNo } }); //foreach (Document d in doc) //{ // EndUser user = new EndUser(); // user.AutoID = d["AutoID"].ToString(); // user.EnduserName = d["EnduserName"].ToString(); // user.Identities = d["Identities"].ToString().Split('|'); // user.IsValid = bool.Parse(d["IsValid"].ToString()); // user.LastModifyTime = DateTime.Parse(d["LastModifyTime"].ToString()); // user.SimCardNo = d["SimCardNo"].ToString(); // userList.Add(user); //} msg = "删除成功"; mongo.Disconnect(); return true; } catch (Exception ex) { msg = ex.Message; mongo.Disconnect(); return false; } }
/// <summary> ///获取集合 /// </summary> /// <param name="person"></param> /// <returns></returns> public List <T> List(int pageIndex, int pageSize, Expression <Func <T, bool> > func, out int pageCount) { pageCount = 0; using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); pageCount = Convert.ToInt32(collection.Count()); var personList = collection.Linq().Where(func).Skip(pageSize * (pageIndex - 1)) .Take(pageSize).Select(i => i).ToList(); mongo.Disconnect(); return(personList); } catch (Exception) { mongo.Disconnect(); throw; } } }
public MongoService() { var mongo = new Mongo(); mongo.Connect(); IMongoDatabase mongoDatabase = mongo.GetDatabase(ConfigurationManager.AppSettings["Database"]); _collection = mongoDatabase.GetCollection<Entity>("entity"); }
static void Main(string[] args) { int numItems = 100000; DateTime start, end; var mongo = new Mongo(); mongo.Connect(); var db = mongo.GetDatabase("test"); var logs = db.GetCollection("logs"); var query = logs.FindAll(); start = DateTime.Now; for (int i = 0; i < numItems; i++) { var log = new Document(); log["DateInserted"] = DateTime.Now; log["SeqNum"] = Guid.NewGuid(); log["Reference"] = String.Format("Hey {0}", i.ToString()); logs.Insert(log); } end = DateTime.Now; Console.WriteLine("Inserted " + numItems + " in " + end.Subtract(start).TotalMilliseconds + "ms"); Console.ReadLine(); }
public void GetMongoDBData() { var mongo = new Mongo(); mongo.Connect(); //Get the blog database. If it doesn't exist, that's ok because MongoDB will create it //for us when we first use it. Awesome!!! var db = mongo.GetDatabase("blog"); //Get the Post collection. By default, we'll use //the name of the class as the collection name. Again, //if it doesn't exist, MongoDB will create it when we first use it. var collection = db.GetCollection<Post>(); //this deletes everything out of the collection so we can run this over and over again. collection.Remove(p => true); //Create a Post to enter into the database. var post = new Post() { Title = "My First Post", Body = "This isn't a very long post.", CharCount = 27, Comments = new List<Comment> { { new Comment() { TimePosted = new DateTime(2010,1,1), Email = "*****@*****.**", Body = "This article is too short!" } }, { new Comment() { TimePosted = new DateTime(2010,1,2), Email = "*****@*****.**", Body = "I agree with Bob." } } } }; collection.Save(post); }
static void Main(string[] args) { var firstNames = new[] { "Tim", "Dave", "Craig", "Noah", "Mark", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; var lastNames = new[] { "Rayburn", "O'Hara", "Neuwirt", "Coad", "Mikaelis" }; var daf = new DictionaryAdapterFactory(); var da = daf.GetAdapter<IPatient>(new Document() .Add("FirstName", "Tim") .Add("LastName", "Rayburn") .Add("Address", new Document().Add("Line1","Dallas,TX"))); using (var mongo = new Mongo()) { var db = mongo.GetDatabase("StElmo"); var coll = db.GetCollection<Patient>().Linq().Select(p => p.FirstName == "Tim").ToList(); var query = from p in db.GetCollection<Patient>().Linq() where p.FirstName == "Tim" select p; } Console.WriteLine(da.FirstName); Console.WriteLine(da.Address.Line1); Console.WriteLine("Complete"); Console.ReadLine(); }
void Test() { //Create a default mongo object. This handles our connections to the database. //By default, this will connect to localhost, //port 27017 which we already have running from earlier. var mongo = new Mongo(); mongo.Connect(); //Get the blog database. If it doesn't exist, that's ok because MongoDB will create it //for us when we first use it. Awesome!!! var db = mongo.GetDatabase("blog"); //Get the Post collection. By default, we'll use //the name of the class as the collection name. Again, //if it doesn't exist, MongoDB will create it when we first use it. var collection = db.GetCollection<Test>(); //this deletes everything out of the collection so we can run this over and over again. collection.Delete(p => true); //Create a Post to enter into the database. var test = new Test("Test1", null, Types.Programming, "Lesnik"); //Save the post. This will perform an upsert. As in, if the post //already exists, update it, otherwise insert it. collection.Save(test); }
public long CountAll(out string msg) { Mongo mongo = new Mongo(connectionString); MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; try { mongo.Connect(); List<EndUser> userList = new List<EndUser>(); IEnumerable<Document> doc = mongoCollection.FindAll().Documents; foreach (Document d in doc) { EndUser user = new EndUser(); user.AutoID = d["AutoID"].ToString(); user.EnduserName = d["EnduserName"].ToString(); user.Identities = d["Identities"].ToString().Split('|'); user.IsValid = bool.Parse(d["IsValid"].ToString()); user.LastModifyTime = DateTime.Parse(d["LastModifyTime"].ToString()); user.SimCardNo = d["SimCardNo"].ToString(); userList.Add(user); } //Document[] docs= doc.ToArray<Document>(); msg = "查询成功"; mongo.Disconnect(); return userList.Count; } catch (Exception ex) { msg = ex.Message; mongo.Disconnect(); return 0; } }
/// <summary> ///读取单条记录 /// </summary> /// <param name="person"></param> /// <returns></returns> public T Single(Expression <Func <T, bool> > func) { using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); var single = collection.Linq().FirstOrDefault(func); mongo.Disconnect(); return(single); } catch (Exception) { mongo.Disconnect(); throw; } } }
static void Main(string[] args) { Mongo mongo = new Mongo(connectionString); //定义一个文档对象,存入两个键值对 mongo.Connect(); //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; //获取collectionName对应的集合,不存在则自动创建 MongoCollection <Document> mongoCollection = mongoDatabase.GetCollection <Document>(collectionName) as MongoCollection <Document>; try { Document doc = new Document(); doc["ID"] = 1; doc["Msg"] = "Hello World!"; //将这个文档对象插入集合 mongoCollection.Insert(doc); //在集合中查找键值对为ID=1的文档对象 Document docFind = mongoCollection.FindOne(new Document { { "ID", 1 } }); //输出查找到的文档对象中键“Msg”对应的值,并输出 Console.WriteLine(Convert.ToString(docFind["Msg"])); } finally { //关闭链接 mongo.Disconnect(); } }
public MongoEventStore(string connectionString, ITypeCatalog typeCatalog) { var connectionStringBuilder = new MongoConnectionStringBuilder(connectionString); var configuration = BuildMongoConfiguration(typeCatalog, connectionString); var mongo = new Mongo(configuration); mongo.Connect(); database = mongo.GetDatabase(connectionStringBuilder.Database); }
public void insertData(qzsImgModel model) { using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); var db = mongo.GetDatabase(databaseString); var collection = db.GetCollection<qzsImgModel>(); collection.Insert(model); } }
public void Insert(IEnumerable<DomainEvent> domainEvents) { using(var mongo = new Mongo(configuration)) { mongo.Connect(); var database = mongo.GetDatabase(databaseName); var eventsCollection = database.GetCollection<DomainEvent>("events"); eventsCollection.Insert(domainEvents); } }
public List<qzsImgModel> selectData100() { List<qzsImgModel> im = new List<qzsImgModel>(); using (Mongo mongo = new Mongo(connectionString)) { mongo.Connect(); var db = mongo.GetDatabase(databaseString); var collecton = db.GetCollection<qzsImgModel>().Find(x => x.qzsFormat == 100).Sort("{qzsUpdateTime:-1}").Documents.ToList(); im.AddRange(collecton); } return im; }
public IEnumerable<DomainEvent> GetEventsByEventTypes(IEnumerable<Type> domainEventTypes) { using(var mongo = new Mongo(configuration)) { mongo.Connect(); var database = mongo.GetDatabase(databaseName); var selector = new Document {{"_t", new Document {{"$in", domainEventTypes.Select(t => t.Name).ToArray()}}}}; var cursor = database.GetCollection<DomainEvent>("events").Find(selector); return cursor.Documents.ToList(); } }
/// <summary> /// 记录日志 /// </summary> /// <param name="ex">出错的信息</param> public static void LogRecord(Exception ex) { Mongo mongoDBLog = null; try { mongoDBLog = new Mongo(ConfigurationManager.AppSettings["mongoDBConfig"]); mongoDBLog.Connect(); var dbLog = mongoDBLog.GetDatabase("USTALogs"); var collection = dbLog.GetCollection<USTALogs>(DateTime.Now.Date.ToString("yyyy-MM-dd")); USTALogs ustaLogs = new USTALogs { errorTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), errorURL = HttpContext.Current.Request.Url.ToString(), accessIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], errorCode = System.Runtime.InteropServices.Marshal.GetHRForException(ex).ToString(), errorObject = ex.Source, errorStackTrace = ex.StackTrace, errorMessage = ex.Message, errorHelpLink = ex.HelpLink, errorMethod = (ex.TargetSite == null ? string.Empty : ex.TargetSite.ToString()) }; collection.Insert(ustaLogs); } catch (Exception mongoDBLogException) { string mongoDBInfoError = HttpContext.Current.Server.MapPath("/LogFiles/WriteMongoDBInfoError_" + DateTime.Now.Date.ToString("yyyy-MM-dd")); if (!System.IO.File.Exists(mongoDBInfoError)) { System.IO.File.Create(mongoDBInfoError); } } finally { if (mongoDBLog != null) { mongoDBLog.Disconnect(); mongoDBLog.Dispose(); } } ////错误信息 //string exceptionMessage = "\n出错页面地址为:" + HttpContext.Current.Request.Url.ToString() + "\n\n访问者IP为:" + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] + "\n" + "\n异常码为:" + System.Runtime.InteropServices.Marshal.GetHRForException(ex) + "\n出错对象为:" + ex.Source + "\n堆栈信息为:" + ex.StackTrace + "\n出错函数为:" + ex.TargetSite + "\n出错信息为:" + ex.Message + "\n参考帮助链接为:" + ex.HelpLink + "\n\n"; ////记录错误日志 //log.Error(exceptionMessage); }
public void GivenIHaveNoProfileProperties() { using (var mongo = new Mongo()) { mongo.Connect(); IMongoDatabase db = mongo.GetDatabase("MetaProfiler"); IMongoCollection mongoCollection = db.GetCollection("ProfileProperties"); mongoCollection.Remove(new Document()); mongo.Disconnect(); } }
public IEnumerable<DomainEvent> GetEvents(Guid aggregateRootId, int startSequence) { using(var mongo = new Mongo(configuration)) { mongo.Connect(); var database = mongo.GetDatabase(databaseName); var eventsCollection = database.GetCollection<DomainEvent>("events").Linq(); return (from domainEvent in eventsCollection where domainEvent.AggregateRootId == aggregateRootId where domainEvent.Sequence > startSequence select domainEvent).ToList(); } }
static void Main(string[] args) { WebClient wc = new WebClient(); string dane = wc.DownloadString("http://nbp.pl/kursy/xml/LastA.xml"); //sciagniety xml XmlSerializer serial = new XmlSerializer(typeof(TabelaKursow)); byte[] bajts = Encoding.UTF8.GetBytes(dane); TabelaKursow tk = serial.Deserialize(new MemoryStream(bajts)) as TabelaKursow; Mongo mg = new Mongo(); mg.Connect(); var db = mg.GetDatabase("waluty"); var collection = db.GetCollection<TabelaKursow>(); Console.WriteLine("Ilosc dokumentow: {0}", collection.Count()); collection.Insert(tk); }
public List<GeoCity> GetCitiesByLatitudeLongitudeRadius(double latitude, double longitude, int radiusMiles) { using (var mongo = new Mongo(ConfigurationManager.ConnectionStrings["GeoServer"].ConnectionString)) { mongo.Connect(); var geoDB = mongo.GetDatabase("geo"); var citiesCollection = geoDB.GetCollection<GeoCity>("cities"); var filterDocument = new Document(); filterDocument.Add("Coord", new Document().Add("$within", new Document().Add("$center", new object[] { new double[] { latitude, longitude }, radiusMiles / 60.0 }))); filterDocument.Add("G3GeoID", new Document().Add("$ne", null)); var foundCities = citiesCollection.Find(filterDocument).Documents.Distinct(new GeoCityComparer()).OrderBy(city => city.GoogleCode).ToList(); mongo.Disconnect(); return foundCities; } }
public void TestCode() { //链接字符串 string connectionString = "mongodb://localhost"; //数据库名 string databaseName = "myDatabase"; //集合名 string collectionName = "myCollection"; //定义Mongo服务 Mongo mongo = new Mongo(connectionString); //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; //获取collectionName对应的集合,不存在则自动创建 MongoCollection<T> mongoCollection = mongoDatabase.GetCollection<T>(collectionName) as MongoCollection<T>; //链接数据库 mongo.Connect(); try { //定义一个文档对象,存入两个键值对 T doc = new T(); doc["ID"] = 1; doc["Msg"] = "Hello World!"; //将这个文档对象插入集合 mongoCollection.Insert(doc); //在集合中查找键值对为ID=1的文档对象 T docFind = mongoCollection.FindOne(new T { { "ID", 1 } }); //输出查找到的文档对象中键“Msg”对应的值,并输出 Console.WriteLine(Convert.ToString(docFind["Msg"])); } finally { //关闭链接 mongo.Disconnect(); } }
public Document InsertMongoData() { //链接字符串 string connectionString = "mongodb://localhost"; //数据库名 string databaseName = "myDatabase"; //集合名 string collectionName = "myCollection"; //定义Mongo服务 Mongo mongo = new Mongo(connectionString); //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; //获取collectionName对应的集合,不存在则自动创建 MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; //链接数据库 mongo.Connect(); try { //定义一个文档对象,存入两个键值对 Document doc = new Document(); doc["ID"] = 1; doc["Msg"] = "Hello World!"; //将这个文档对象插入集合 mongoCollection.Insert(doc); //在集合中查找键值对为ID=1的文档对象 Document docFind = mongoCollection.FindOne(new Document { { "ID", 1 } }); //输出查找到的文档对象中键“Msg”对应的值,并输出 txtContent.Text = Convert.ToString(docFind["Msg"]); } finally { //关闭链接 mongo.Disconnect(); } }
static void Main(string[] args) { //Create a default mongo object. This handles our connections to the database. //By default, this will connect to localhost, port 27017 //Need to have started server by running mongod var mongo = new Mongo(); mongo.Connect(); //Get the database var db = mongo.GetDatabase("company"); //Get the Employee collection. var collection = db.GetCollection<Employee>(); //this deletes everything out of the collection so we can run this over and over again. //collection.Delete(p => true); //Create employees to enter into the database. CreateEmployees(collection); //count all the employees var totalNumberOfEmployees = collection.Count(); //count employees with exactly one project var query1 = collection.Count(e => e.Projects.Count == 1); // get all employees var query2 = from e in collection.Linq() select e; IList<Employee> emps = query2.ToList<Employee>(); // //find names of employees on a specific project var query3 = from e in collection.Linq() where e.Projects.Any(p => p.ProjectName == "Secret Project") select e.Name; foreach (var name in query3) { Console.WriteLine(name); } Console.ReadLine(); }
public static IMongoDatabase UsePool(params string[] keys) { int count = pool.Count; if (count != poolkey.Count || count == 0) { pool.Clear(); factorys.Clear(); poolkey.Clear(); count = 0; ConnectionStringSettingsCollection conns = WebConfig.GetConn(); foreach (ConnectionStringSettings info in conns) { string key = info.Name; if (info.ProviderName != "MongoDB" || keys.IndexOf(key) == -1) continue; Mongo factory = new Mongo(info.ConnectionString); factory.Connect(); factorys[key.ToLower()] = factory; pool[key.ToLower()] = factory.GetDatabase(key.IndexOf(".") == -1 ? key : key.Split('.')[1]); poolkey.Add(key.ToLower()); count++; } } return pool[poolkey[count == 1 ? 0 : Rand.RndInt(0, count)]]; }
public static Document FindOne(string mongoConnsring, string mongoDbName, string mongoCollectionName, object spec) { using (Mongo mongo = new Mongo(mongoConnsring)) { //获取databaseName对应的数据库,不存在则自动创建 MongoDatabase mongoDatabase = mongo.GetDatabase(mongoDbName) as MongoDatabase; //获取collectionName对应的集合,不存在则自动创建 MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(mongoCollectionName) as MongoCollection<Document>; //链接数据库 mongo.Connect(); ////在集合中查找键值对为ID=1的文档对象 Document docFind = mongoCollection.FindOne(spec); mongo.Disconnect(); return docFind; } }
/// <summary> /// 更新操作 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Update(T t, Expression <Func <T, bool> > func) { using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); collection.Update <T>(t, func, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } }
/// <summary> /// 插入操作 /// </summary> /// <param name="person"></param> /// <returns></returns> public void Insert(T t) { using (MongoDB.Mongo mongo = new MongoDB.Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection <T>(collectionName); collection.Insert(t, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } }
private void ConnectMongo() { var mongo = new Mongo(); mongo.Connect(); var db = mongo.GetDatabase("AdvicesDB"); _collection = db.GetCollection<AdvicesSubject>(); // collection.Remove(p => true); }
public bool UpdateEndusers(EndUser[] newUsers, out string msg) { Mongo mongo = new Mongo(connectionString); MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; try { mongo.Connect(); for (int i = 0; i < newUsers.Length; ++i) { List<EndUser> userList = new List<EndUser>(); Document enduser1 = new Document(); enduser1["AutoID"] = newUsers[i].AutoID; enduser1["EnduserName"] = newUsers[i].EnduserName; enduser1["SimCardNo"] = newUsers[i].SimCardNo; enduser1["Identities"] = getIdentitiesString(newUsers[i].Identities); enduser1["LastModifyTime"] = newUsers[i].LastModifyTime; enduser1["IsValid"] = newUsers[i].IsValid; Document doc = new Document { { "SimCardNo", newUsers[i].SimCardNo } }; if (doc == null) { msg = "不存在该SIM卡号:" + newUsers[i].SimCardNo.ToString(); mongo.Disconnect(); return false; } mongoCollection.Update(new Document("$set", enduser1), doc); } msg = "更新成功"; mongo.Disconnect(); return true; } catch (Exception ex) { msg = ex.Message; mongo.Disconnect(); return false; } }
private bool DeleteAll() { Mongo mongo = new Mongo(connectionString); MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; mongo.Connect(); try { mongoCollection.Remove(new Document { }); mongo.Disconnect(); return true; } catch { mongo.Disconnect(); return false; } }
public bool UpdateEnduser(EndUser newUser, out string msg) { Mongo mongo = new Mongo(connectionString); MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; try { mongo.Connect(); List<EndUser> userList = new List<EndUser>(); Document enduser1 = new Document(); enduser1["AutoID"] = newUser.AutoID; enduser1["EnduserName"] = newUser.EnduserName; enduser1["SimCardNo"] = newUser.SimCardNo; enduser1["Identities"] = getIdentitiesString(newUser.Identities); enduser1["LastModifyTime"] = newUser.LastModifyTime; enduser1["IsValid"] = newUser.IsValid; Document doc = new Document { { "SimCardNo", newUser.SimCardNo } }; if (doc == null) { msg = "不存在该SIM卡号"; mongo.Disconnect(); return false; } mongoCollection.Update(new Document("$set", enduser1), doc); //IEnumerable<Document> doc2 = mongoCollection.Find(new Document { { "SimCardNo", newUser.SimCardNo } }).Documents; //foreach (Document d in doc2) //{ // EndUser user = new EndUser(); // user.AutoID = d["AutoID"].ToString(); // user.EnduserName = d["EnduserName"].ToString(); // user.Identities = d["Identities"].ToString().Split('|'); // user.IsValid = bool.Parse(d["IsValid"].ToString()); // user.LastModifyTime = DateTime.Parse(d["LastModifyTime"].ToString()); // user.SimCardNo = d["SimCardNo"].ToString(); // userList.Add(user); //} msg = "更新成功"; mongo.Disconnect(); return true; } catch (Exception ex) { msg = ex.Message; mongo.Disconnect(); return false; } }
public IEnumerable<DomainEvent> GetEventsBySelector(Document selector, int skip, int limit) { using(var mongo = new Mongo(configuration)) { mongo.Connect(); var database = mongo.GetDatabase(databaseName); var cursor = database.GetCollection<DomainEvent>("events").Find(selector); return cursor.Skip(skip).Limit(limit).Documents.ToList(); } }
public EndUser[] SelectEnduserByName(string iEnduserName, out string msg) { Mongo mongo = new Mongo(connectionString); MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; try { mongo.Connect(); List<EndUser> userList = new List<EndUser>(); MongoRegex reg = new MongoRegex(".*" + iEnduserName + ".*", MongoRegexOption.IgnoreCase); Document docEnduserName = new Document { { "name", reg } }; IEnumerable<Document> doc = mongoCollection.Find(docEnduserName).Documents; foreach (Document d in doc) { EndUser user = new EndUser(); user.AutoID = d["AutoID"].ToString(); user.EnduserName = d["EnduserName"].ToString(); user.Identities = d["Identities"].ToString().Split('|'); user.IsValid = bool.Parse(d["IsValid"].ToString()); user.LastModifyTime = DateTime.Parse(d["LastModifyTime"].ToString()); user.SimCardNo = d["SimCardNo"].ToString(); userList.Add(user); } msg = "查询成功"; mongo.Disconnect(); return userList.ToArray(); } catch (Exception ex) { msg = ex.Message; mongo.Disconnect(); return null; } }
public bool InsertEndusers(EndUser[] newUsers, out string msg) { Mongo mongo = new Mongo(connectionString); MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; try { mongo.Connect(); for (int i = 0; i < newUsers.Length; ++i) { IEnumerable<Document> doc = mongoCollection.Find(new Document { { "SimCardNo", newUsers[i].SimCardNo } }).Documents; if (doc == null || doc.Count() == 0) { Document enduser1 = new Document(); enduser1["AutoID"] = newUsers[i].AutoID; enduser1["EnduserName"] = newUsers[i].EnduserName; enduser1["SimCardNo"] = newUsers[i].SimCardNo; enduser1["Identities"] = getIdentitiesString(newUsers[i].Identities); enduser1["LastModifyTime"] = newUsers[i].LastModifyTime; enduser1["IsValid"] = newUsers[i].IsValid; mongoCollection.Save(enduser1); } else { msg = "用户已存在"; mongo.Disconnect(); return false; } } msg = "插入成功"; mongo.Disconnect(); return true; } catch (Exception ex) { msg = ex.Message; mongo.Disconnect(); return false; } }
static void Main(string[] args) { //Creamos el objecto mongo por defecto que se encarga de nuestras conexiones a la BD //por defecto, se conecta a localhost en el puerto 27017, en el que debería estar escuchando el servidor var mongo = new Mongo(); mongo.Connect(); //obtenemos la BD blog. si no existe mongoDB la creará la primera vez que la usemos var db = mongo.GetDatabase("blog"); //Obtenemos la colección Post. Por defecto, utilizaremos el nombre de la clase como el nombre de la //colección. Igualmente que arriba, si no existe será creada en su primer uso. var collection = db.GetCollection<Post>(); //esto borra todo de la colección cada vez que corremos el programa collection.Remove(p => true); //creamos los posts para ingresar a la BD CrearPosts(collection); //contamos todos los posts var nroTotalPosts = collection.Count(); //contamos posts con solo un comentario var nroPostsCon1Comentario = collection.Count(p => p.Comentarios.Count == 2); //contamos posts en los que comentó tupapa var postsDeTupapa = from p in collection.Linq() where p.Comentarios.Any(c => c.Email.StartsWith("tupapa")) select p.Titulo; //obtenemos los títulos y comentarios de los posts que tenga comentarios después del primero de enero var postsDespuésDel1ero = from p in collection.Linq() where p.Comentarios.Any(c => c.FechaPosteo > new DateTime(2014, 1, 1)) select new { Title = p.Titulo, Comments = p.Comentarios }; //encontramos posts con menos de 40 caracteres var postsConMenosDe40Chars = from p in collection.Linq() where p.Longitud < 40 select p; //obtenemos el número de caracteres en total de todos los posts //manual map-reduce (para efectos de comparación) var sum = Convert.ToInt32(collection.MapReduce() .Map(new Code(@" function() { emit(1, this.CharCount); }")) .Reduce(new Code(@" function(key, values) { var sum = 0; values.forEach(function(prev) { sum += prev; }); return sum; }")) .Documents.Single()["value"]); //usamos linq para construir automáticamente la consulta de arriba //como vemos es muchísimo más simple var linqSum = (int)collection.Linq().Sum(p => p.Longitud); //crear manualmente la sgte consulta sería tediosísimo var stats = from p in collection.Linq() where p.Comentarios.Any(c => c.Email.StartsWith("troll")) group p by p.Longitud < 40 into g select new { LessThan40 = g.Key, Sum = g.Sum(x => x.Longitud), Count = g.Count(), Average = g.Average(x => x.Longitud), Min = g.Min(x => x.Longitud), Max = g.Max(x => x.Longitud) }; //corremos nuestro form Application.Run(new BlogFrm(collection)); }