当前位置: 首页>>代码示例>>C#>>正文


C# MongoCollection.Find方法代码示例

本文整理汇总了C#中MongoCollection.Find方法的典型用法代码示例。如果您正苦于以下问题:C# MongoCollection.Find方法的具体用法?C# MongoCollection.Find怎么用?C# MongoCollection.Find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在MongoCollection的用法示例。


在下文中一共展示了MongoCollection.Find方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetDocuments

 protected virtual IEnumerable<BsonDocument> GetDocuments(MongoCollection<BsonDocument> collection)
 {
     var query = Filter();
     return query != null
         ? collection.Find(query)
         : collection.FindAll();
 }
开发者ID:GusLab,项目名称:video-portal,代码行数:7,代码来源:CollectionMigration.cs

示例2: HandleOneStep

        private Level2FlightRecord HandleOneStep(int currentSecond, int step, FlightParameter para,
            LevelTopFlightRecord topRecord, Flight flight, MongoCollection<Level1FlightRecord> collection)
        {
            IMongoQuery query = Query.And(Query.EQ("ParameterID", new BsonString(para.ParameterID)),
                Query.GTE("FlightSecond", new BsonInt32(currentSecond)),
                Query.LT("FlightSecond", new BsonInt32(currentSecond + step)));

            MongoCursor<Level1FlightRecord> flightRecord = collection.Find(query);

            Level2FlightRecord level2 = new Level2FlightRecord()
            {
                StartSecond = currentSecond,
                EndSecond = Math.Min(flight.EndSecond, currentSecond + step),
                // Level1FlightRecords = flightRecord.ToArray(),
                ParameterID = para.ParameterID,
            };

            //var sum = from one in level2.Level1FlightRecords
            //          select one.ValueCount;
            //level2.Count = sum.Sum();

            //var avg = from one in level2.Level1FlightRecords
            //          select one.AvgValue;
            //level2.AvgValue = avg.Sum() * level2.Count;

            //var min = from one in level2.Level1FlightRecords
            //          select one.MinValue;
            //level2.MinValue = min.Min();

            //var max = from one in level2.Level1FlightRecords
            //          select one.MaxValue;
            //level2.MaxValue = max.Max();

            return level2;
        }
开发者ID:K-Library-NET,项目名称:PopcornStudios,代码行数:35,代码来源:DefaultLevel1ToLevelTopRecordStrategy.cs

示例3: Modify

    private static void Modify(MongoCollection<Log> logs)
    {
        Console.WriteLine("UPDATE");

        var query = Query.EQ("LogType.State", "pending");
        var update = Update.Set("Text", "Changed to 'closed'").Set("LogType.State", "closed");
        logs.Update(query, update, UpdateFlags.Multi);

        logs.Find(Query.EQ("Text", "Changed to 'closed'")).Print();
    }
开发者ID:MarKamenov,项目名称:TelerikAcademy,代码行数:10,代码来源:MongoCRUD.cs

示例4: InsertOrUpdateByFlightID

        /// <summary>
        /// 根据FlightID插入或更新一个架次信息,插入的是实体,使用Common库
        /// </summary>
        /// <param name="flight"></param>
        /// <param name="flightResult">flightResult才是真正要返回的结果,因为flight如果是需要新增的,则不会有MongoDB需要的ObjectId</param>
        /// <param name="modelCollection"></param>
        /// <returns></returns>
        private static Flight InsertOrUpdateByFlightID(
            FlightDataEntities.Flight flight, Flight flightResult, MongoCollection<Flight> modelCollection)
        {
            try
            {
                IMongoQuery q1 = Query.EQ("FlightID", new MongoDB.Bson.BsonString(flight.FlightID));

                var cursor = modelCollection.Find(q1);
                //第一次查询,是判断是否需要UPDATE
                if (cursor != null && cursor.Count() > 0)
                {
                    foreach (var value in cursor.AsEnumerable())
                    {
                        value.FlightName = flight.FlightName;
                        value.Aircraft = flight.Aircraft;
                        value.EndSecond = flight.EndSecond;
                        value.StartSecond = flight.StartSecond;
                        modelCollection.Save(value);

                        flightResult = value;
                    }
                }
                else
                {//如果INSERT,就必须插入之后才有ObjectId,需要返回带有ObjectId的对象(不单单只考虑WCF返回没带有ObjectId的情况)
                    modelCollection.Insert(flight);

                    var cursor2 = modelCollection.Find(q1);
                    if (cursor2 != null && cursor2.Count() > 0)
                    {
                        flightResult = cursor2.First();
                    }
                    else flightResult = null;
                }
            }
            catch (Exception e)
            {
                LogHelper.Error("InsertOrUpdateByFlightID", e);
                flightResult = null;
            }

            return flightResult;
        }
开发者ID:niravpatel,项目名称:PopcornStudios,代码行数:49,代码来源:DataInputServiceBll.cs

示例5: CreateIndex

        public static void CreateIndex(MongoCollection<TweetItem> collection)
        {
            DateTime dtmFirst = new DateTime(2014, 05, 17, 0, 0, 0);
            DateTime dtmLast = new DateTime(2014, 05, 17, 23, 59, 59);
            FSDirectory dir = FSDirectory.GetDirectory(Environment.CurrentDirectory + "\\LuceneIndex");
            //Lucene.Net.Store.RAMDirectory dir = new RAMDirectory();
            Lucene.Net.Analysis.StopAnalyzer an = new Lucene.Net.Analysis.StopAnalyzer();
            IndexWriter wr = new IndexWriter(dir, an, true);
            IStemmer stemmer = new EnglishStemmer();
            while (dtmFirst.Date <= DateTime.Now.Date)
            {
                var query = Query<TweetItem>.Where(t => t.CreationDate >= dtmFirst && t.CreationDate <= dtmLast);
                List<TweetItem> value = collection.Find(query).ToList();
                //DirectoryInfo diMain = new DirectoryInfo(dia.SelectedPath);               
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://www.datasciencetoolkit.org/text2sentiment");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    foreach (TweetItem tweet in value)
                    {
                        Document doc = new Document();
                        
                        //SentimentResult res = await GetSentiment(tweet.Text, client);                        
                        string stemmedtext = PerformStemming(stemmer, NLPToolkit.Tokenizer.TokenizeNow(tweet.Text).ToArray());
                        var scores = classifier.Classify(stemmedtext,DragonHelper.DragonHelper.ExcludeList);
                        string positiveSentiment = string.Empty;
                        string negativeSentiment = string.Empty;                        
                        positiveSentiment = scores["Positive"].ToString();
                        negativeSentiment = scores["Negative"].ToString();
                        doc.Add(new Field("id", tweet._id.ToString(), Field.Store.YES, Field.Index.NO));
                        doc.Add(new Field("created", tweet.CreationDate.ToString(), Field.Store.YES, Field.Index.NO));
                        doc.Add(new Field("user", tweet.User, Field.Store.YES, Field.Index.NO));                        
                        doc.Add(new Field("text", stemmedtext, Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES));                        
                        doc.Add(new Field("possentiment", positiveSentiment , Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES));
                        doc.Add(new Field("negsentiment", negativeSentiment, Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.YES));

                        wr.AddDocument(doc);
                    }
                }
                dtmFirst = dtmFirst.AddDays(1);
                dtmLast = dtmLast.AddDays(1);
            }
            wr.Optimize();
            wr.Flush();
            wr.Close();
            dir.Close();
        }
开发者ID:peac3maker,项目名称:TwitterSentimentAnalysis,代码行数:49,代码来源:Program.cs

示例6: TaskQueue

        // http://www.yoda.arachsys.com/csharp/singleton.html 线程安全的模式
        // 静态构造函数用于初始化任何静态数据,或用于执行仅需执行一次的特定操作。在创建第一个实例或引用任何静态成员之前将调用静态构造函数。
        static TaskQueue()
        {
            tasks = new List<SpiderTask>();
            agents = new List<Agent>();
            siteCollection = (DependencyResolver.Current.GetService(typeof(IMongoRepo<Site>)) as IMongoRepo<Site>).Collection;
            taskModelCollection = (DependencyResolver.Current.GetService(typeof(IMongoRepo<TaskModel>)) as IMongoRepo<TaskModel>).Collection;

            //注意必须使用ToList避免懒惰加载,否则在每次调用taskModels对象时会再次查询,从而清空已被赋值过的Timer属性。
            //这里应该是mongo driver或mongo Respository的特殊模式。
            taskModels = taskModelCollection.AsQueryable<TaskModel>().Where(d => d.Act == (int)eAct.Normal && d.Interval > 0).ToList();
            sites = siteCollection.Find(Query<Site>.EQ(d => d.Act, (int)eAct.Normal)).ToList();
            Instance = new TaskQueue();
            Instance.ModelTimerBuild();
            Instance.Maintenance();
        }
开发者ID:zicjin,项目名称:SpiderMan,代码行数:17,代码来源:TaskQueue.cs

示例7: Logon

 public Logon()
 {
     InitializeComponent();
     ArrayList list = new ArrayList();
     MongoServer server = MongoServer.Create();
     MongoDatabase exerHist = server.GetDatabase("exerHist");
     names = exerHist.GetCollection<BsonDocument>("names");
     var query = new QueryDocument();
     foreach (BsonDocument name in names.Find(query))
     {
         string nameToAdd = name["name"].ToString();
         list.Add(nameToAdd);
         searchList.Add(nameToAdd.ToLower());
     }
     list.Sort();
     nameCB.ItemsSource = list;
 }
开发者ID:guozanhua,项目名称:Kinect-Tracking-Project,代码行数:17,代码来源:Logon.xaml.cs

示例8: DoWork

        private void DoWork(MongoCollection<BsonDocument> collection)
        {
            var rand = new Random();
            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                var i = rand.Next(0, 10000);
                List<BsonDocument> docs;
                try
                {
                    docs = collection.Find(Query.EQ("i", i))
                        .ToList();
                }
                catch
                {
                    Console.Write("+");
                    continue;
                }

                if (docs.Count == 0)
                {
                    try
                    {
                        collection.Insert(new BsonDocument("i", i));
                    }
                    catch
                    {
                        Console.Write("*");
                    }
                }
                else
                {
                    try
                    {
                        var filter = new QueryDocument("_id", docs[0]["_id"]);
                        var update = new UpdateDocument("$set", new BsonDocument("i", i + 1));
                        collection.Update(filter, update);
                        //Console.Write(".");
                    }
                    catch (Exception)
                    {
                        Console.Write("*");
                    }
                }
            }
        }
开发者ID:RavenZZ,项目名称:MDRelation,代码行数:45,代码来源:LegacyApi.cs

示例9: EnsureSession

        public MessageSessionInfo EnsureSession(string appName, string sessionId, ObjectId from, ObjectId to, MongoCollection<MessageSessionInfo> collection)
        {
            var session = collection.Find(Query.EQ("session_id", sessionId)).SetFields("session_id", "user_1", "user_2", "user1_is_deleted", "user2_is_deleted").FirstOrDefault();

            if (session == null)
            {
                session = new MessageSessionInfo()
                {
                    SessionId = sessionId,
                    User1 = from,
                    User2 = to,
                    Messages = new MessageInfo[0],
                    LastUpdated = DateTime.Now,
                    UnreadMessagesUser1 = 0,
                    UnreadMessagesUser2 = 0
                };
                collection.EnsureIndex("session_id");
                collection.Insert(session);
            }
            return session;
        }
开发者ID:xoperator,项目名称:GoKapara,代码行数:21,代码来源:UserMessagesDataProvider.cs

示例10: GetHereArticles

        private IEnumerable<ArticleWebDto> GetHereArticles(
            MongoCollection<ArticleDto> articles,
            string lngString,
            string latString,
            CultureInfo culture)
        {
            var distance = 2.0d;
            var maxDistanceString = (distance / EarthRadius).ToString(culture.NumberFormat);

            var jsonQuery = "{ 'location' : { $geoWithin : { $centerSphere : [ [ " + lngString + " , " + latString + " ] , " + maxDistanceString + " ] } } }";

            var doc = BsonSerializer.Deserialize<BsonDocument>(jsonQuery);
            var query = new QueryDocument(doc);
            var results = articles.Find(query).SetSortOrder(new SortByBuilder().Descending("publishedAt")).SetLimit(50);

            var dtos = results.ToList().Select(ConvertArticleDtoToArticleWebDto());

            return dtos;
        }
开发者ID:Cosmo,项目名称:News-Sightseeing,代码行数:19,代码来源:DiscoverController.cs

示例11: CreateCursor

        private MongoCursor<BsonDocument> CreateCursor(MongoCollection<BsonDocument> collection, SimpleExpression criteria)
        {
            if (criteria == null)
                return collection.FindAll();

            var mongoQuery = _expressionFormatter.Format(criteria);
            return collection.Find(mongoQuery);
        }
开发者ID:kppullin,项目名称:Simple.Data.MongoDB,代码行数:8,代码来源:MongoAdapterFinder.cs

示例12: GroupDetails

        public static void GroupDetails(MainAppForm mainapp)
        {
            connectionString = Properties.Settings.Default.ServerOne;
            client = new MongoClient(connectionString);
            server = client.GetServer();
            gebase = server.GetDatabase("gebase");

            string paneltext;

            try
            {
                var number = Properties.Settings.Default.CurrentGroupNumber;
                if (number == string.Empty)
                {
                    paneltext = "nothing selected";
                }
                else
                {
                    paneltext = String.Format("group {0} details", number);
                }
                mainapp.bandedDetailGroupGridView.GroupPanelText = paneltext;

                stdcollection = gebase.GetCollection<stdcolls>("stds");
                var query = Query.EQ("group", number);

                var stddetails = new BindingList<stdcolls>(stdcollection.Find(query).ToList());
                mainapp.gridGroupDetail.DataSource = stddetails;
            }
            catch
            {
                return;
            }
        }
开发者ID:rootah,项目名称:gebase-alpha-0.2.1,代码行数:33,代码来源:stdcode.cs

示例13: GetMongoSessionObject

 public SessionObject GetMongoSessionObject(MongoCollection<SessionObject> collection, string sessionID) {
     var query = Query<SessionObject>.EQ(x => x.BsonID, SessionObject.GetBsonId(this._applicationName, sessionID));
     return collection.Find(query).FirstOrDefault();
 }
开发者ID:bkrauska,项目名称:MongoDB.Session,代码行数:4,代码来源:MongoSessionHelper.cs

示例14: GetLastEntryInOpLog

        public static void GetLastEntryInOpLog(MongoCollection<BsonDocument> collection)
        {
            BsonValue lastId = BsonMinKey.Value;
            string connectionString = ConfigurationManager.ConnectionStrings["RulesEntities"].ConnectionString;
            while (true)
            {
                Console.WriteLine("Query last changed data");
                var query = Query.GT("ts", lastId);
                var cursor = collection.Find(query)
                    .SetFlags(QueryFlags.TailableCursor | QueryFlags.AwaitData)
                    .SetSortOrder(SortBy.Ascending("$natural"));

                Console.WriteLine("found {0} record(s)", cursor.Count());
                foreach (var document in cursor)
                {
                    lastId = document["ts"];
                    Console.WriteLine("LastId is {0}", lastId);
                    Console.WriteLine(document);

                    // dynamic data = JObject.Parse(document.ToString());
                    string[] table = document["ns"].ToString().Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                    if (document["op"].ToString() == "i" && table.Length > 2 && table[2].Equals("[OfficeTypeMaster]", StringComparison.OrdinalIgnoreCase))
                    {
                        // string tableName = data.ns.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries)[1];
                        // insert
                        //var assembly = Assembly.GetExecutingAssembly();
                        //var type = assembly.GetTypes()
                        //    .First(t => t.Name == tableName);
                        //var obj = Activator.CreateInstance(type);

                        var mst = new UnitOfWork<OfficeTypeMaster>(connectionString);

                        //var jsonWriterSettings1 = new JsonWriterSettings { OutputMode = JsonOutputMode.TenGen };
                        //var data1 = document["o"].ToJson(jsonWriterSettings1);

                        //var jsonWriterSettings2 = new JsonWriterSettings { OutputMode = JsonOutputMode.Shell };
                        //var data2 = document["o"].ToJson(jsonWriterSettings2);

                        //var jsonWriterSettings3 = new JsonWriterSettings { OutputMode = JsonOutputMode.JavaScript };
                        //var data3 = document["o"].ToJson(jsonWriterSettings3);

                        //foreach (BsonElement elm in document.Elements)
                        //{
                        //    var tt = elm.Name;
                        //}

                        //var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
                        //var data = document["o"].ToJson(jsonWriterSettings);

                        // this works except binary
                        // var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<OfficeTypeMaster1>(data);

                        var data = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<OfficeTypeMaster>(document["o"].ToJson());
                        mst.Repository.Insert(data);
                        mst.Save();
                    }
                }

                Thread.Sleep(TimeSpan.FromMilliseconds(500));
            }
        }
开发者ID:ajayanandgit,项目名称:MongoToSQLSync,代码行数:61,代码来源:Program.cs

示例15: GetPoolRanking

 /// <summary>
 /// Returns the pool ranking, with the first element being the pool winner and the last being the loser.
 /// </summary>
 /// <param name="pool"></param>
 /// <param name="teamCol"></param>
 /// <param name="matchCol"></param>
 /// <returns></returns>
 private static List<Team> GetPoolRanking(int pool, MongoCollection<Team> teamCol)
 {
     return teamCol.Find(Query<Team>.Where(x => x.Pool == pool)).OrderBy(x => x.PoolRank).ToList();
 }
开发者ID:jvanvugt,项目名称:lolcognac-website,代码行数:11,代码来源:RiotApiScrapeJob.cs


注:本文中的MongoCollection.Find方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。