private HttpResponseMessage GetCsvOutput(MongoCursor<BsonDocument> ClinicalViews, int userRole) { Dictionary<string, string> cvNormalizedDataItem; List<Dictionary<string, string>> cvNormalizedData = new List<Dictionary<string, string>>(); List<string> cvColumnHeaders = new List<string>(); //Build Matrix from records foreach (BsonDocument doc in ClinicalViews) { var singleCVDocument = JObject.Parse(doc.ToString()); cvNormalizedDataItem = new Dictionary<string, string>(); foreach (var singleCVDocumentField in singleCVDocument) { if (singleCVDocumentField.Value.Children().Count() > 0) foreach (JProperty datapointField in singleCVDocumentField.Value) { //if (datapointField.Name != "DatapointId" && datapointField.Name != "RestrictEntriesList" && datapointField.Name != "RestrictViewsList") if (datapointField.Name.ToLower() == "data") { //string keyname = singleCVDocumentField.Key + "_" + datapointField.Name; //cvNormalizedDataItem.Add(keyname, datapointField.Value.ToString()); //cvColumnHeaders.Add(keyname); cvNormalizedDataItem.Add(singleCVDocumentField.Key, datapointField.Value.ToString()); cvColumnHeaders.Add(singleCVDocumentField.Key); } } else { cvNormalizedDataItem.Add(singleCVDocumentField.Key, singleCVDocumentField.Value.ToString()); cvColumnHeaders.Add(singleCVDocumentField.Key); } } cvNormalizedData.Add(cvNormalizedDataItem); } List<string> noDupesHeaders = cvColumnHeaders.Distinct().ToList(); StringBuilder oneLine = new StringBuilder(); List<string> results = new List<string>(); //CSV Header foreach (string strheader in noDupesHeaders) { oneLine.Append(strheader + ","); } results.Add(oneLine.Remove(oneLine.Length - 1, 1).ToString()); //CSV Body foreach (Dictionary<string, string> item in cvNormalizedData) { oneLine = new StringBuilder(); foreach (string strheader in noDupesHeaders) { try { oneLine.Append("\"" + item[strheader] + "\","); } catch { oneLine.Append(","); } } results.Add(oneLine.Remove(oneLine.Length - 1, 1).ToString()); } return Request.CreateResponse(HttpStatusCode.OK, results, new CsvMediaFormatter()); }
private void ApplyFields(MongoCursor<BsonDocument> cursor, IEnumerable<SimpleReference> columns) { if (columns == null || !columns.Any()) return; var fields = columns.Select(x => string.Join(".", x.ToString().Split('.').Skip(1))) .Select(x => MongoIdKeyComparer.DefaultInstance.Equals(x, "id") ? "_id" : x); cursor.SetFields(fields.ToArray()); }
private static IList<JSonReport> ToList(MongoCursor<JSonReport> cursor) { List<JSonReport> resultAsList = new List<JSonReport>(); foreach (var item in cursor) { resultAsList.Add(item); } return resultAsList; }
/// <summary> /// Finishes profiling for 'command', recording durations. /// </summary> public void ExecuteFinishImpl(Guid id, MongoCursor reader = null) { var current = _inProgress[id]; current.ExecutionComplete(isReader: reader != null); MongoTiming ignore; _inProgress.TryRemove(id, out ignore); if (reader != null) { _inProgressCursors[reader] = current; } }
/// <summary> /// 解析内容数据返回内容公共类集合 /// </summary> /// <param name="bds">基础数据集</param> /// <returns>内容公共类集合</returns> public static IList<PublicContent> ContentResolve(MongoCursor<BsonDocument> bds) { IList<PublicContent> objlist = new List<PublicContent>(); foreach (BsonDocument bd in bds) { ContentType contentType = (ContentType)Enum.Parse(typeof(ContentType), bd["ContentType"].AsInt32.ToString()); switch (contentType) { case ContentType.Interest: InterestContent interest = new InterestContent(); interest = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<InterestContent>(bd.ToJson()); objlist.Add((PublicContent)interest); break; case ContentType.Member: MemberContent member = new MemberContent(); member = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<MemberContent>(bd.ToJson()); objlist.Add((PublicContent)member); break; case ContentType.CallFor: CallForContent callfar = new CallForContent(); callfar = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<CallForContent>(bd.ToJson()); objlist.Add((PublicContent)callfar); break; case ContentType.Image: ImageContent image = new ImageContent(); image = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<ImageContent>(bd.ToJson()); objlist.Add((PublicContent)image); break; case ContentType.InterView: InterViewContent interview = new InterViewContent(); interview = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<InterViewContent>(bd.ToJson()); objlist.Add((PublicContent)interview); break; case ContentType.IWant: IWantContent iwant = new IWantContent(); iwant = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<IWantContent>(bd.ToJson()); objlist.Add((PublicContent)iwant); break; case ContentType.Mood: MoodContent mood = new MoodContent(); mood = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<MoodContent>(bd.ToJson()); objlist.Add((PublicContent)mood); break; case ContentType.SuiSuiNian: SuiSuiNianContent suisuinian = new SuiSuiNianContent(); suisuinian = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<SuiSuiNianContent>(bd.ToJson()); objlist.Add((PublicContent)suisuinian); break; } } return objlist; }
public static void Test_MongoDB_FindAll_02 <T>(string collection) { Trace.WriteLine("Test_MongoDB_FindAll_02"); MongoDatabase mdb = GetMongoDatabase(); //MongoCollectionSettings<T> colSettings = new MongoCollectionSettings<T>(mdb, collection); //colSettings.ReadPreference.ReadPreferenceMode = ReadPreferenceMode.Nearest; //colSettings.WriteConcern = new WriteConcern(); MongoCollection <T> mcollection = mdb.GetCollection <T>(collection); MongoCursor <T> mcursor = mcollection.FindAll(); mcursor.SetLimit(10); //RunSource.CurrentRunSource.View(mcursor); mcursor.zView(); }
private List <Entities.Prevoz> popuniPrevoz() { var connectionString = "mongodb://localhost/?safe=true"; var server = MongoServer.Create(connectionString); var db = server.GetDatabase("TouristGuide"); var collection = db.GetCollection <Entities.Prevoz>("prevozi"); //MongoCursor<Radnik> radnici = collection.FindAll(); MongoCursor <Entities.Prevoz> opstina = collection.FindAll(); return(opstina.ToList <Entities.Prevoz>()); }
private List <Opstina> vratiOpstine() { var connectionString = "mongodb://localhost/?safe=true"; var server = MongoServer.Create(connectionString); var db = server.GetDatabase("TouristGuide"); var collection = db.GetCollection <Opstina>("opstine"); //MongoCursor<Radnik> radnici = collection.FindAll(); MongoCursor <Opstina> opstina = collection.FindAll(); return(opstina.ToList <Opstina>()); }
public void Init(Action callback) { MongoCursor <BsonDocument> list = MongoDBHelper.Search(collectionName); Video v = null; if (list != null) { foreach (BsonDocument doc in list) { v = new Video(doc); this.videoList.Add(v); } } foreach (string path in Config.VIDEO_PATH) { CheckVideo(path); } //// 将重复的classType删除 //Dictionary<string, List<ClassType>> repeatClassType = ClassTypeManager.GetInstance().GetRepeatClassType(); //// 遍历所有video //foreach (var video in videoList) //{ // // 遍历所有重复的classType // foreach (var keyVal in repeatClassType) // { // foreach (var classType in keyVal.Value) // { // // 一旦发现video中包含了重复的classType // // 就把video中重复的classType都删掉,然后加入repeatClassType中的第一个classType // if (video.ClassList.Contains(classType.ID)) // { // int index = 0; // foreach (var classType1 in keyVal.Value) // { // if (index++ > 0) // { // classType1.NeedDelete = true; // } // video.ClassList.Remove(classType1.ID); // } // video.ClassList.Add(keyVal.Value[0].ID); // break; // } // } // } //} callback(); }
public MongoCursor <T> FindAll <T>(MongoCollection <T> collection) { MongoCursor <T> result = null; try { result = collection.FindAll(); } catch (Exception) { } return(result); }
private SearchResults KeysToSearchResults(IEnumerable <BsonValue> keys) { MongoCursor cursor = collection.Find(Query.In(InternalField.ID, keys)).SetFields(InternalField.SELFLINK); var results = new SearchResults(); foreach (BsonDocument document in cursor) { string id = document.GetValue(InternalField.SELFLINK).ToString(); Uri rid = new Uri(id, UriKind.Relative); // NB. these MUST be relative paths. If not, the data at time of input was wrong results.Add(rid); } return(results); }
private void BuildStainResult(BsonDocument bsonSurgicalSpecimen, string surgicalSpecimenId) { MongoCollection stainResultTable = this.m_SQLTransferDatabase.GetCollection <BsonDocument>("tblStainResult"); MongoCursor mongoCursor = stainResultTable.FindAs <BsonDocument>(Query.EQ("SurgicalSpecimenId", surgicalSpecimenId)); BsonArray bsonArray = new BsonArray(); foreach (BsonDocument bsonStainResult in mongoCursor) { bsonArray.Add(bsonStainResult); } bsonSurgicalSpecimen.Add("StainResultItemCollection", bsonArray); }
public List <Comic> GetComics() { MongoClient client = new MongoClient("mongodb://localhost/?safe=true"); MongoServer server = client.GetServer(); var database = server.GetDatabase("comicclub"); var collection = database.GetCollection <Comic>("comic"); MongoCursor <Comic> stripovi = collection.FindAll().SetSortOrder(SortBy.Descending("numberLikes")); List <Comic> comics = stripovi.ToList(); return(comics); }
public List <Comment> GetComments() { MongoClient client = new MongoClient("mongodb://localhost/?safe=true"); MongoServer server = client.GetServer(); var database = server.GetDatabase("comicclub"); var collection = database.GetCollection <Comment>("comment"); MongoCursor <Comment> komentari = collection.FindAll(); List <Comment> comments = komentari.ToList(); return(comments); }
private void btnAdd_Click(object sender, EventArgs e) { var connectionString = "mongodb://localhost/?safe=true"; var server = MongoServer.Create(connectionString); var database = server.GetDatabase("TouristGuide"); var collection = database.GetCollection <Bolnica>("bolnice"); var opstine = database.GetCollection <Opstina>("opstine"); MongoCursor <Opstina> ops = opstine.FindAll(); Opstina o = new Opstina(); if (azuriranje == null) { foreach (Opstina op in ops) { if (op.Naziv == cbxOpstina.SelectedItem.ToString()) { o = op; } } } Bolnica b = new Bolnica { Naziv = txtNaziv.Text, Adresa = txtAdresa.Text, Opstina = new MongoDBRef("opstine", o.Id) }; if (azuriranje == null) { collection.Insert(b); o.Bolnice.Add(new MongoDBRef("bolnice", b.Id)); opstine.Save(o); } else { var query = (from bolnice in collection.AsQueryable <Bolnica>() where bolnice.Id == azuriranje.Id select bolnice).FirstOrDefault(); query.Naziv = txtNaziv.Text; query.Adresa = txtAdresa.Text; collection.Save(query); } this.Close(); }
public List <User> GetUsers() { MongoClient client = new MongoClient("mongodb://localhost/?safe=true"); MongoServer server = client.GetServer(); var database = server.GetDatabase("comicclub"); var collection = database.GetCollection <User>("user"); MongoCursor <User> korisnici = collection.FindAll(); List <User> users = korisnici.ToList(); return(users); }
private void btnAdd_Click(object sender, EventArgs e) { if (validateForm()) { bool f = true; //just for initialization string ad_type = "F.E."; if (rdfe.Checked == true) { ad_type = "F.E."; } else if (rddse.Checked == true) { ad_type = "D.S.E."; } MongoClient client = new MongoClient("mongodb://localhost"); MongoServer server = client.GetServer(); MongoDatabase db = server.GetDatabase("NBA"); MongoCursor <Students> put = db.GetCollection <Students>("Students").FindAll(); foreach (Students i in put) { //if prn no already exists give error if (txtprn.Text == i.prn) { f = false; MessageBox.Show("PRN No already exists!"); txtprn.Focus(); break; } } //if prn does not exists if (f) { MongoCollection <BsonDocument> Students = db.GetCollection <BsonDocument>("Students"); BsonDocument student = new BsonDocument { { "prn", txtprn.Text.Trim() }, { "student_name", txtstudent_name.Text.Trim() }, { "academicyear", cmbacademicyear.Text.Trim() }, { "ad_type", ad_type }, { "migration", cmbMigration.Text.Trim() } }; Students.Insert(student); MessageBox.Show("Record Added Successfully"); refresh(); } clear(); } }
private void ExportAssetHours() { try { XmlDocument xmlDocument = (XmlDocument)exportHoursDocumentBase.Clone(); MongoCursor <BsonDocument> cursor = GetUnexportedAssetHours(); if (cursor.Count() > 0) { logger.LogInfo("Exporting found unexported asset timesheet entries", cursor.Count()); StartBatch(xmlDocument, "EfiAifBuffProjJournalTable"); } else { logger.LogFineTrace("No unexported timesheet entries found. (for assets)"); return; } List <TimesheetEntryFragment> timesheetEntryFragments = GetTimesheetFragmentsForAssets(cursor); logger.LogInfo(cursor.Count() + " timesheet entries produced " + timesheetEntryFragments.Count + " fragments. (for assets)"); int exportedFragments = ExportAssetTimesheetFragmentsToXml(timesheetEntryFragments, xmlDocument); if (exportedFragments > 0) { logger.LogInfo("Saving exported fragments to disk.", exportedFragments); WriteExportedDataToDisk(xmlDocument, FilePrefixHourData); AssetTimesheetEntriesExported += exportedFragments; AssetTimesheetEntryFilesCreated++; } else { logger.LogInfo("No valid timesheet entry fragments found to export. Not saving XML document."); } MarkEntriesAsExported(cursor, "assetentry"); } catch (Exception ex) { logger.LogError("Exporting hours failed (for assets).", ex); AssetTimesheetEntryExportsFailed++; } finally { EndBatch(); } }
public IEnumerable <AggregatedValue> Find(DateTime startDate, DateTime endDate, Dictionary <string, List <string> > props) { MongoCollection <StoredCounter> items = MongoDb.GetCollection <StoredCounter>("countersData"); IMongoQuery q = Query.And(Query.GTE("date", startDate), Query.LT("date", endDate)); FieldsBuilder fields = new FieldsBuilder(); //fields.Include("date", "data.Max", "data.Min", "data.Count", "data.Avg", "data.Sum"); fields.Include("date", "data"); foreach (KeyValuePair <string, List <string> > prop in props) { string fieldName = "props." + prop.Key; fields.Include(fieldName); if (prop.Value.Count == 0) { q = Query.And(q, Query.Exists(fieldName)); } else if (prop.Value.Count == 1) { q = Query.And(q, Query.EQ(fieldName, prop.Value.First())); } else { q = Query.And(q, Query.In(fieldName, prop.Value.Cast <BsonString>())); } } MongoCursor cursor = items.Find(q); cursor.SetFields(fields); cursor.SetSortOrder(SortBy.Ascending("date")); Stopwatch sw = Stopwatch.StartNew(); var found = cursor.Cast <object>().ToList(); sw.Stop(); Console.WriteLine(found.Count + " entries fetched from db in " + sw.ElapsedMilliseconds + " ms"); sw.Restart(); var parsed = found.Cast <StoredCounter>().Select(ParseAggregatedValue).ToList(); sw.Stop(); Console.WriteLine(parsed.Count + " entries parsed in " + sw.ElapsedMilliseconds + " ms"); sw.Restart(); var result = parsed.Compact().ToList(); sw.Stop(); Console.WriteLine(found.Count + " entries compacted to " + result.Count + " in " + sw.ElapsedMilliseconds + " ms"); return(result); }
public void show_doc(string doc_id) { try { string str_query = "{'doc_id':'" + doc_id + "'}"; MongoCursor <BsonDocument> cursor = MongoHelper.query_cursor_from_string(str_query); show_cursor_in_txt(cursor); show_cursor_in_tv(cursor); this.dgv_result.DataSource = MongoHelper.get_table_from_cursor(cursor); } catch (Exception error) { this.txt_result.Text = error.Message; } }
private void button1_Click(object sender, EventArgs e) { MongoClient client = new MongoClient("mongodb://localhost"); MongoServer server = client.GetServer(); MongoDatabase db = server.GetDatabase("projecttest"); MongoCollection <BsonDocument> Transaction = db.GetCollection <BsonDocument>("Transaction"); MongoCursor <Class2> put = db.GetCollection <Class2>("Transaction").FindAll(); dataGridView1.RowCount = 1; dataGridView1.ColumnCount = 5; foreach (Class2 i in put) { dataGridView1.Rows.Add(Convert.ToString(i._id), i.Seller, Convert.ToString(i.Creditcrdno).Trim(), Convert.ToString(i.Totalamount), Convert.ToString(i.Accno)); } }
public List <T> Page <T>(System.Linq.Expressions.Expression <Func <T, bool> > expression, int skip, int limit, string orderBy) where T : class, new() { IMongoQuery query = Query <T> .Where(expression); MongoCursor <T> cursor = mongoDb.GetCollection <T>(GetTypeName(typeof(T))).Find(query); cursor.SetSkip(skip).SetLimit(limit); if (!String.IsNullOrEmpty(orderBy)) { cursor.SetSortOrder(SortBy.Descending(orderBy)); } return(cursor.ToList()); }
public void Initialize(MongoCollection <HtmlRecord> records) { MongoCursor <HtmlRecord> cursor = records.FindAll(); if (cursor.Count() > 0) { foreach (HtmlRecord record in cursor) { Job job = new Job(record.id, JobStatus.None, record.timeStamp); jobSet.Add(record.id, job); jobSchedule.Enqueue(record.timeStamp, record.id); jobStatus.Add(record.id, RecordStatus.Waiting); } } }
private void button1_Click(object sender, EventArgs e) { var connectionString = "mongodb://localhost/?safe=true"; var server = MongoServer.Create(connectionString); var database = server.GetDatabase("Rina"); var collection = database.GetCollection <Imena>("Imena"); MongoCursor <Imena> imena = collection.FindAll(); foreach (Imena i in imena.ToArray <Imena>()) { MessageBox.Show(i.ime); } }
private void FormNaruci_Load(object sender, EventArgs e) { var connectionString = "mongodb://localhost/?safe=true"; var server = MongoServer.Create(connectionString); var database = server.GetDatabase("Biblioteka"); var collection = database.GetCollection <Knjiga>("knjige"); MongoCursor <Knjiga> knjige = collection.FindAll(); foreach (Knjiga k in knjige) { comboBox1.Items.Add(k.naslov); } }
public BsonDocument GetProject(MongoCursor <BsonDocument> cursor, string projectName, string runTimeVersion) { BsonDocument ret = new BsonDocument(); if (cursor.Count() != 0) { ret = cursor.First(); } else { ret.Add("@project-name", projectName); ret.Add("@runtime-version", runTimeVersion); } return(ret); }
/// <summary> /// Get paged items /// </summary> /// <param name="query"></param> /// <param name="startIndex">start from 0</param> /// <param name="pageSize"></param> /// <param name="sortBy"></param> /// <returns></returns> public virtual List <T> GetItems(IMongoQuery query, int startIndex, int pageSize, SortByDocument sortBy) { if (startIndex <= 0) { startIndex = 0; } sortBy = InitSortBy(sortBy); MongoCursor <T> cursor = this.DbContext.Collection.Find(query) .SetSortOrder(sortBy) .SetSkip(startIndex).SetLimit(pageSize); return(cursor.ToList()); }
public IEnumerable <object> GetById(IEnumerable <string> keys) { if (keys.Count() == 0) { yield break; } var bsonIdArray = new BsonArray(keys); MongoCursor cursor = _collection.FindAs(_documentType, Query.In("_id", bsonIdArray)); foreach (var doc in cursor) { yield return(doc); } }
IList <BsonDocument> getAllDocuments(string collectionName) { IList <BsonDocument> docList = new List <BsonDocument>(); using (_ms.RequestStart(_mdb)) { MongoCollection mc = _mdb.GetCollection("csharp"); MongoCursor <BsonDocument> cur = mc.FindAllAs <BsonDocument> (); System.Collections.Generic.IEnumerator <BsonDocument> e = cur.GetEnumerator(); while (e.MoveNext()) { docList.Add(e.Current); } } return(docList); }
private void BuildSpecimenOrder(BsonDocument bsonParent) { MongoCollection specimenOrderTable = this.m_SQLTransferDatabase.GetCollection <BsonDocument>("tblSpecimenOrder"); MongoCursor mongoCursor = specimenOrderTable.FindAs <BsonDocument>(Query.EQ("MasterAccessionNo", bsonParent.GetValue("MasterAccessionNo"))); BsonArray array = new BsonArray(); foreach (BsonDocument bsonChild in mongoCursor) { bsonChild.Add("AssemblyQualifiedName", typeof(YellowstonePathology.Business.Specimen.Model.SpecimenOrder).AssemblyQualifiedName); array.Add(bsonChild); this.BuildAliquotOrder(bsonChild); } bsonParent.Add("SpecimenOrderCollection", array); }
public bool Verify(ApiKey apiKey) { MongoCollection <ApiKeyDocument> keys = _db.GetCollection <ApiKeyDocument>(ApiKeyDocument.Collection); ObjectId id = apiKey.AsId(); MongoCursor <ApiKeyDocument> findOne = keys.Find( Query.And( Query <ApiKeyDocument> .EQ(d => d.Id, id), Query <ApiKeyDocument> .NE(d => d.Confirmed, null) )) .SetFields(Fields <ApiKeyDocument> .Include(d => d.Id)) .SetLimit(1); return(findOne.SingleOrDefault() != null); }
private void frmReport_Load(object sender, EventArgs e) { MongoClient client = new MongoClient("mongodb://localhost"); MongoServer server = client.GetServer(); MongoDatabase db = server.GetDatabase("NBA"); MongoCursor <Students> put = db.GetCollection <Students>("Students").FindAll(); foreach (Students i in put) { if (!cmbacademicyear.Items.Contains(i.academicyear)) { cmbacademicyear.Items.Add(i.academicyear); } } }
/// <summary> /// Splits a collection of objects into an unknown number of pages with n items per page (for example, if I have a list of 45 shoes and say 'shoes.Partition(10)' I will now have 4 pages of 10 shoes and 1 page of 5 shoes. /// </summary> /// <typeparam name="T">The type of object the collection should contain.</typeparam> /// <param name="superset">The collection of objects to be divided into subsets.</param> /// <param name="pageSize">The maximum number of items each page may contain.</param> /// <returns>A subset of this collection of objects, split into pages of maximum size n.</returns> public static IEnumerable <IEnumerable <T> > Partition <T>(this MongoCursor <T> superset, int pageSize) { if (superset.Count() < pageSize) { yield return(superset); } else { var numberOfPages = Math.Ceiling(superset.Count() / (double)pageSize); for (var i = 0; i < numberOfPages; i++) { yield return(superset.Skip(pageSize * i).Take(pageSize)); } } }
public static YellowstonePathology.Business.Client.Model.ClientCollection GetClientsByClientName(string clientName) { YellowstonePathology.Business.Client.Model.ClientCollection result = new YellowstonePathology.Business.Client.Model.ClientCollection(); YellowstonePathology.Business.Mongo.Server server = new Business.Mongo.TestServer(YellowstonePathology.Business.Mongo.MongoTestServer.LISDatabaseName); MongoCollection collection = server.Database.GetCollection <BsonDocument>("Client"); MongoCursor cursor = collection.FindAs <BsonDocument>(Query.Matches("ClientName", BsonRegularExpression.Create("^" + clientName + ".*", "i"))); foreach (BsonDocument bsonDocument in cursor) { YellowstonePathology.Business.Client.Model.Client client = (YellowstonePathology.Business.Client.Model.Client)YellowstonePathology.Business.Mongo.BSONObjectBuilder.Build(bsonDocument, typeof(YellowstonePathology.Business.Client.Model.Client)); result.Add(client); } return(result); }
/// <summary> /// Filters the specified query. /// </summary> /// <param name="query">The query.</param> /// <returns></returns> public IQueryable <T> Filter(Dictionary <string, string> filterParams) { var queries = new List <IMongoQuery>(); if (filterParams.Count > 0) { foreach (var item in filterParams) { queries.Add(Query.EQ(item.Key, item.Value)); } } MongoCursor <T> cursor = collection.Find(Query.And(queries)); return(cursor.AsQueryable <T>()); }
static void consoleBsonDocument(MongoCursor<BsonDocument> bsoncursor) { if (bsoncursor.Count() > 0) { foreach (BsonDocument bson in bsoncursor) { Console.WriteLine("CustomerName:" + bson["CustomerName"].AsString); Console.WriteLine("Address:" + bson["Address"].AsString); Console.WriteLine("Tel:" + bson["Tel"].AsString); } } else { Console.WriteLine("未找到所需要数据"); } }
private void ApplySorting(MongoCursor<BsonDocument> cursor, IEnumerable<SimpleOrderByItem> orderings) { if (orderings == null || !orderings.Any()) return; var sortBuilder = new SortByBuilder(); foreach (var ordering in orderings) { var name = ExpressionFormatter.GetFullName(ordering.Reference); if (ordering.Direction == OrderByDirection.Ascending) sortBuilder.Ascending(name); else sortBuilder.Descending(name); } cursor.SetSortOrder(sortBuilder); }
/// <summary> /// 获取多条按To用户分组累加组的魅力值 /// </summary> /// <param name="mgCurs">Mongo数据集游标</param> /// <returns>用户编号和魅力值键值对列表</returns> public static Dictionary<String, float> GetGlamourCountToMemberGroupAccumulate(MongoCursor<GlamourCounts> mgCurs) { //按用户分组累加组的魅力值 var qGlamourCounts = from glamCount in mgCurs group glamCount by glamCount.ToMember into toMemberList select new { toMemberList.Key, memberGlamourCount = toMemberList.Sum(glamCount => glamCount.Value) }; //按键值对取出用户和魅力值 Dictionary<String, float> memberGlamourCounts = new Dictionary<String, float>(); foreach (var glamCout in qGlamourCounts) { memberGlamourCounts.Add(glamCout.Key, glamCout.memberGlamourCount); } return memberGlamourCounts; }
internal void Set(MongoCursor cursor) { if (cursor == null) return; if (Skip != -1) { cursor.Skip = Skip; } if (Limit != -1) { cursor.Limit = Limit; } if (Fields != null) { cursor.Fields = Fields; } if (SortBy != null) { cursor.SetSortOrder(SortBy); } }
void IMongoDbProfiler.ReaderFinish(MongoCursor reader) { MongoProfiler.ReaderFinish(reader); }
void IMongoDbProfiler.ExecuteFinish(Guid id, MongoCursor reader) { MongoProfiler.ExecuteFinish(id, reader); }
/// <summary> /// 查询结果生成DataTable /// </summary> /// <param name="result">传入BsonDcoument集合MongoCursor</param> /// <returns>DataTable</returns> public static DataTable get_table_from_cursor(MongoCursor<BsonDocument> result) { DataTable table = new DataTable(); //插入列 foreach (BsonDocument doc in result) { foreach (BsonElement test in doc.Elements) { string str_name = test.Name; bool is_has = false; foreach (DataColumn column in table.Columns) { if (column.ColumnName == str_name) { is_has = true; } } if (is_has == false) { table.Columns.Add(str_name); } } } //插入列 foreach (BsonDocument doc in result) { DataRow row_new = table.NewRow(); foreach (BsonElement test in doc.Elements) { row_new[test.Name.ToString()] = test.Value.ToString(); } table.Rows.Add(row_new); } return table; }
/// <summary> /// 将MongoCursor转化为DataTable《未实现》 /// </summary> /// <param name="mc">输入MongoCursor</param> /// <returns>生成的DataTable</returns> public static DataTable ConverMongoCursorToDataTable(MongoCursor mc) { DataTable dt = new DataTable(); //列的初始化 foreach (string column in mc) { } //生成行 foreach (BsonDocument item in mc) { } return dt; }
private void ApplySkip(MongoCursor<BsonDocument> cursor, int? skipCount) { if (skipCount.HasValue) cursor.SetSkip(skipCount.Value); }
/// <summary> /// Called when 'reader' finishes its iterations and is closed. /// </summary> public static void ReaderFinish(this MongoProfiler mongoProfiler, MongoCursor reader) { if (mongoProfiler == null) return; mongoProfiler.ReaderFinishImpl(reader); }
private void PopulateLabel(MongoCursor<Subscriber> subscribers) { foreach (Subscriber subscriber in subscribers) { PopulateLabel(subscriber); } }
public void show_cursor_in_txt(MongoCursor<BsonDocument> cursor) { this.txt_result.Text = ""; foreach (BsonDocument doc in cursor) { this.txt_result.Text += doc.ToString() + Environment.NewLine; } this.txt_result.Text = JsonBeautify.beautify(this.txt_result.Text); }
public void show_cursor_in_tv(MongoCursor<BsonDocument> cursor) { tv_result.Nodes.Clear(); TreeNode node_root = new TreeNode("Query Document"); int i = 0; foreach (BsonDocument doc in cursor) { TreeNode item = new TreeNode(); item.Text = i.ToString(); i = i + 1; add_doc_to_node(doc, ref item); node_root.Nodes.Add(item); } this.tv_result.Nodes.Add(node_root); //this.tv_result.ExpandAll(); }
private void DataLoaded(MongoCursor<BsonDocument> data) { try { if (data == null) { return; } bool alt = true; _nextItemId = 0; data.ToList().ForEach(item => { AddItems(item.ToArray(), 0, alt, null, item["_id"].AsBsonValue); alt = !alt; }); _pager.PropertyChanged += PagerPropertyChanged; } catch (Exception ex) { Utilities.LogException(ex); } finally { if (BusyStateChanged != null) BusyStateChanged(false, null); } }
private IEnumerable<KeyValuePair<string, FlightRawData[]>> TransformToFlightRawData(string[] parameterIds, MongoCursor<Level1FlightRecord> cursor) { Dictionary<string, List<Level1FlightRecord>> datas = new Dictionary<string, List<Level1FlightRecord>>(); Dictionary<string, List<FlightRawData>> resultMap = new Dictionary<string, List<FlightRawData>>(); if (parameterIds == null || parameterIds.Length == 0) { Dictionary<string, string> paramIdtmp = new Dictionary<string, string>(); foreach (var rec in cursor) { if (!paramIdtmp.ContainsKey(rec.ParameterID)) { paramIdtmp.Add(rec.ParameterID, rec.ParameterID); datas.Add(rec.ParameterID, new List<Level1FlightRecord>()); resultMap.Add(rec.ParameterID, new List<FlightRawData>()); } else { datas[rec.ParameterID].Add(rec); } } parameterIds = paramIdtmp.Keys.ToArray(); } else { foreach (string key in parameterIds) { if (!datas.ContainsKey(key)) { datas.Add(key, new List<Level1FlightRecord>()); resultMap.Add(key, new List<FlightRawData>()); } } foreach (var c in cursor) { if (datas.ContainsKey(c.ParameterID)) datas[c.ParameterID].Add(c); } } foreach (string k in datas.Keys) { var values = datas[k]; foreach (var v in values) { IEnumerable<FlightRawData> rawDatas = v.ToRawDatas(); if (rawDatas != null && rawDatas.Count() > 0) resultMap[k].AddRange(rawDatas); } } var result = from two in resultMap select new KeyValuePair<string, FlightRawData[]>( two.Key, two.Value.ToArray()); return result; }
/// <summary> /// Called when 'reader' finishes its iterations and is closed. /// </summary> public void ReaderFinishImpl(MongoCursor reader) { MongoTiming stat; // this reader may have been disposed/closed by reader code, not by our using() if (_inProgressCursors.TryGetValue(reader, out stat)) { stat.ReaderFetchComplete(); MongoTiming ignore; _inProgressCursors.TryRemove(reader, out ignore); } }
private void ApplyTake(MongoCursor<BsonDocument> cursor, int? takeCount) { if (takeCount.HasValue) cursor.SetLimit(takeCount.Value); }
/// <summary> /// Creates a new GetMoreRequest with the provided MongoCursor /// </summary> public GetMoreRequest(MongoCollection collection, MongoCursor cursor, int count) : base(OpCodeTypes.GetMore, collection) { Cursor = cursor; Count = count; }
private static void PrepareCursorForBatchProcessing(MongoCursor cursor) { cursor.SetBatchSize(1024); cursor.SetFlags(QueryFlags.NoCursorTimeout); }
/// <summary> /// Recursive method that removes id from the list of departments if all of its children are present in the list and their children don't have children ... /// </summary> /// <param name="departments">The list of all department ids</param> /// <param name="cursor">Mongo Cursor, providing acces to the list of all departments</param> /// <param name="parents"></param> private static void RemoveIfAllChildrenArePresentOrThereAreNoChildren(List<ObjectId> departments, MongoCursor<Department> cursor, List<ObjectId> parents) { var localParents = new List<ObjectId>(parents); foreach (var dep in localParents) { ObjectId pId = dep; //Get all children var children = cursor.Where(o => o.DepartmentOf == pId).Select(o => o.Id).Distinct().ToList(); //If no children, remove department if (children.Count() == 0) { parents.Remove(dep); } else { //Validate whether all children are present in the departments if (children.Except(departments).Count() == 0) { //Validate if their children have children RemoveIfAllChildrenArePresentOrThereAreNoChildren(departments, cursor, children); //If no children, remove department if (children.Count() == 0) { parents.Remove(dep); } } } } }
/// <summary> /// Finishes profiling for 'command', recording durations. /// </summary> public static void ExecuteFinish(this MongoProfiler mongoProfiler, Guid id, MongoCursor reader = null) { if (mongoProfiler == null) return; mongoProfiler.ExecuteFinishImpl(id, reader); }
public Result(MongoCursor<BsonDocument> cursor) { Cursor = cursor; Index = -1; }
private HttpResponseMessage GetjsonOutput(MongoCursor<BsonDocument> ClinicalViews, int userRole) { List<string> results = new List<string>(); int i=0; foreach (BsonDocument doc in ClinicalViews) { results.Add(doc.ToString()); i++; } results.Add("{Count:"+ i.ToString() +"}"); return Request.CreateResponse(HttpStatusCode.OK, results); }
/// <summary> /// Selects the records from the database that matches this query /// </summary> public IEnumerable<MongoDocument> Select(int skip, int take, QueryOptionTypes options, params string[] fields) { //create the request to use QueryRequest request = new QueryRequest(this.Collection); request.Fields.AddRange(fields); request.Skip = skip; request.Take = take; request.Options = options; request.Parameters = this._Parameters; //send the request and get the response QueryResponse response = this.Collection.Database.Connection .SendRequest(request) as QueryResponse; //save this cursor for later MongoCursor cursor = new MongoCursor(request, response.CursorId, response.TotalReturned); this.Collection.Database.RegisterCursor(cursor); //and return the records IEnumerable<MongoDocument> documents = response.Documents.AsEnumerable(); this.Collection.UpdateOnSubmit(documents); return documents; }