public void TestDescending1() { var sortBy = SortBy <Test> .Descending(x => x.A); string expected = "{ \"a\" : -1 }"; Assert.AreEqual(expected, sortBy.ToJson()); }
public IEnumerable <News> Top(int top, int mode) { var _query = Query <News> .In(x => x.Modes, new int[] { mode }); var _sort = SortBy <News> .Descending(x => x.Created); return(MainDb.Instant.Top <News>(top, _query, _sort)); }
public DateTime GetLastModified(IEnumerable <string> filenames) { return(gfs .Find(Query.In("filename", new BsonArray(filenames))) .SetSortOrder(SortBy.Descending("uploadDate")) .SetLimit(1) .Select(x => x.UploadDate).FirstOrDefault()); }
private ICollection <PersistentEvent> GetOldestEvents(string stackId, PagingOptions options) { return(Find <PersistentEvent>(new MultiOptions() .WithStackId(stackId) .WithFields(FieldNames.Id, FieldNames.OrganizationId, FieldNames.ProjectId, FieldNames.StackId) .WithSort(SortBy.Descending(FieldNames.Date_UTC)) .WithPaging(options))); }
public IEnumerable <Plan> GetLastCreate(int limit) { var results = this.MongoConnectionHandler.MongoCollection.FindAllAs <Plan>() .SetSortOrder(SortBy <Plan> .Descending(g => g.CreateDate)) .SetLimit(limit); return(results); }
public void TestDescendingAscending() { var sortBy = SortBy <Test> .Descending(x => x.A).Ascending(x => x.B); string expected = "{ \"a\" : -1, \"b\" : 1 }"; Assert.Equal(expected, sortBy.ToJson()); }
public IEnumerable <Knowledge> GetLastCreate(int limit) { var knowledges = this.MongoConnectionHandler.MongoCollection.FindAllAs <Knowledge>() .SetSortOrder(SortBy <Knowledge> .Descending(g => g.CreateDate)) .SetLimit(limit); return(knowledges); }
public static void saveCode(string Email, string randomCode) { MongoCollection <User> objCollection = db.GetCollection <User>("c_User"); var query = Query.EQ("Email", Email); var sortBy = SortBy.Descending("_id"); var update = Update.Set("PasswordResetCode", randomCode); var result = objCollection.FindAndModify(query, sortBy, update); }
public bool UpdateSubsription(Subscription subscription) { var query = Query.And(Query.EQ("Email", subscription.EmailId)); var update = MongoDB.Driver.Builders.Update.Set("Allow", subscription.Allow); var sortBy = SortBy.Descending("Email"); FindAndModifyResult result = emailCollection.FindAndModify(query, sortBy, update, true); return(result.Ok); }
public bool Update(Metric2 Metric) { var query = Query.And(Query.EQ("Name", Metric.Name), Query.EQ("Identifier", Metric.Identifier)); var update = MongoDB.Driver.Builders.Update.Inc("Count", 1).Inc("Total", Metric.Total); var sortBy = SortBy.Descending("Name"); FindAndModifyResult result = collection2.FindAndModify(query, sortBy, update, true); return(result.Ok); }
public ActionResult Index() { var connectionString = "mongodb://infjam.cloudapp.net:27017/"; var db = new MongoClient(connectionString).GetServer().GetDatabase("db"); var lastThree = db.GetCollection("news").FindAll().SetSortOrder(SortBy.Descending("_id")).SetLimit(3); ViewBag.News = lastThree; return(View()); }
/// <summary> /// Function for retriving the comments from mongodb. /// </summary> /// <param name="postId"></param> /// <param name="approve"></param> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> /// <param name="order"></param> /// <returns></returns> public IList <Comment> Retrieve(string postId, bool?approve, int?pageNumber, int?pageSize, string order, string parentId) { // Setting up the comment display order. IMongoQuery query = null; IMongoSortBy sortOrder = SortBy <Comment> .Ascending(x => x.Date); //if (order == "Ascending") //{ //sort.Ascending(); sortOrder = SortBy <Comment> .Ascending(x => x.Date); //} if (order == "Descending") { sortOrder = SortBy <Comment> .Descending(x => x.Date); } // Create filter according to postid if (!string.IsNullOrEmpty(postId)) { query = Query <Comment> .EQ(p => p.PostId, postId); } // Append filter according to approve status. if (approve.HasValue) { var approveQuery = Query <Comment> .EQ(p => p.Approved, approve.Value); approveQuery = Query.And(approveQuery, Query <Comment> .EQ(p => p.ParentId, parentId)); query = query == null ? approveQuery : Query.And(query, approveQuery); } // Retrieve the comment if pagesize and pagenumber are given. if (pageSize != null && pageNumber != null) { int pageSizeInt = (int)(pageSize); int offset = (int)(pageSize * (pageNumber - 1)); return (_blogContext.Comments.Find(query) .SetSortOrder(sortOrder) .SetSkip(offset) .SetLimit(pageSizeInt) .ToList()); } // Retrieve the comment if pagesize and pagenumber not given else { return (_blogContext.Comments.Find(query) .SetSortOrder(sortOrder) .ToList()); } }
/// <summary> /// Allows to get all the documents in the collection /// </summary> /// <author> /// Luis Gonzalo Quijada Romero /// </author> /// <returns> /// Returns a Json list with all the documents in the categories collection /// or null if there are no documents /// </returns> public String GetRows(string orderfield = null, string sortBy = "ASC", int limit = 0) { if (orderfield == null) { orderfield = "name"; } var sorting = SortBy.Ascending(orderfield); if (sortBy == "DES") { sorting = SortBy.Descending(orderfield); } try { MongoCursor cursor = null; if (limit == 0) { cursor = collection.FindAllAs(typeof(BsonDocument));//.SetSortOrder(sorting); } else { cursor = collection.FindAllAs(typeof(BsonDocument));//.SetSortOrder(sorting).SetLimit(limit); } List <BsonDocument> documents = new List <BsonDocument>(); foreach (BsonDocument document in cursor) { try { document.Set("_id", document.GetElement("_id").Value.ToString()); try { document.Set("CreatedTimeStamp", document.GetElement("CreatedTimeStamp").Value.ToString()); } catch (Exception ex) { } try { document.Set("status", document.GetElement("status").Value.ToString()); } catch (Exception ex) { } documents.Add(document); } catch { } } return(documents.ToJson()); } catch (Exception e) { return(null); } }
public IQueryable <HistoricalMessage> GetBy(string remoteQueueName, DateTime since, int limit) { var query = Query.And(Query.EQ("RemoteQueueName", remoteQueueName), Query.GTE("DateTime", since)); var messages = _collection.Find(query).SetSortOrder(SortBy.Descending("DateTime")).Take(limit); return(messages.AsQueryable()); }
public int GetMaxId() { var cursor = _mongoCollection.FindAs <T>(null); cursor.SetSortOrder(SortBy.Descending("Rid")); var first = cursor.FirstOrDefault(); return(first != null ? (int)cursor.First().GetType().GetProperty("Rid").GetValue(cursor.First(), null) : 0); }
public void TestPushEachWithPositionAndSortAndSlice() { var update = Update.PushEach("name", new PushEachOptions { Position = 10, Slice = -3, Sort = SortBy.Descending("a") }, _docA1, _docA2); var expected = "{ \"$push\" : { \"name\" : { \"$each\" : [{ \"a\" : 1 }, { \"a\" : 2 }], \"$position\" : 10, \"$slice\" : -3, \"$sort\" : { \"a\" : -1 } } } }"; Assert.Equal(expected, update.ToJson()); }
public void TestPushEachWrappedWithSortAndSlice() { var update = Update.PushEachWrapped("name", new PushEachOptions { Slice = -3, Sort = SortBy.Descending("a") }, _a, _b); var expected = "{ \"$push\" : { \"name\" : { \"$each\" : [{ \"X\" : 1 }, { \"X\" : 2 }], \"$slice\" : -3, \"$sort\" : { \"a\" : -1 } } } }"; Assert.Equal(expected, update.ToJson()); }
public virtual Snapshot GetSnapshot(Guid streamId, int maxRevision) { return(this.TryMongo(() => this.PersistedSnapshots .Find(streamId.ToSnapshotQuery(maxRevision)) .SetSortOrder(SortBy.Descending("_id")) .SetLimit(1) .Select(mc => mc.ToSnapshot(this.serializer)) .FirstOrDefault())); }
public IEnumerable <WantedUser> GetAllWantedUsers(int limit, int skip) { var gamesCursor = this.MongoConnectionManager.MongoCollection.FindAllAs <WantedUser>() .SetSortOrder(SortBy <WantedUser> .Descending(g => g.CreatedDate)) .SetLimit(limit) .SetSkip(skip); return(gamesCursor); }
public static void UpdateFriendListBySelect(string id, string newListName) { MongoCollection <Friends> objCollection = db.GetCollection <Friends>("c_Friends"); var query = Query.EQ("_id", ObjectId.Parse(id)); var sortBy = SortBy.Descending("_id"); var update = Update.Set("BelongsTo", newListName); var result = objCollection.FindAndModify(query, sortBy, update, true); }
public IQueryable <T> Find(Expression <Func <T, bool> > lambda, int pageNumber, int pageSize, out int totalCount) { IMongoQuery query = Query <T> .Where(lambda); totalCount = (int)_collection.Find(query).Count(); IMongoSortBy sortOrder = SortBy.Descending("Timestamp"); return(_collection.Find(query).SetSortOrder(sortOrder).SetSkip((pageNumber - 1) * pageSize).SetLimit(pageSize).AsQueryable()); }
public List <Dictionary <string, object> > ExecuteGetListBykey(string table, string key, object val, string[] fields = null, string sort = "", bool asc = true, int skip = 0, int limt = 0) { List <Dictionary <string, object> > retlist = new List <Dictionary <string, object> >(); try { var cb = check_table(table, key); //IMongoQuery imq = Query.And(new IMongoQuery[]{Query.EQ(key, BsonValue.Create(val)),Query.NotExists(""),}) var ret = cb.Find(Query.EQ(key, BsonValue.Create(val))); if (fields != null) { ret = ret.SetFields(fields); } if (sort != string.Empty) { if (asc) { ret = ret.SetSortOrder(SortBy.Ascending(sort)); } else { ret = ret.SetSortOrder(SortBy.Descending(sort)); } } if (skip > 0) { ret = ret.SetSkip(skip); } if (limt > 0) { ret = ret.SetLimit(limt); } var it = ret.GetEnumerator(); while (it.MoveNext()) { if (it.Current.Contains("_id")) { it.Current.Remove("_id"); } retlist.Add(it.Current.ToDictionary()); } } catch (Exception ex) { Console.WriteLine(ex.Message); retlist.Clear(); } return(retlist); }
public Dictionary <string, List <List <long> > > GetData(string dbName, string aggName, int pageindex, int pagesize, string groupName) { var rootconfig = Configuration.GetConfig(); var c = rootconfig.MemcachedList.Union(rootconfig.KTList).Union(rootconfig.MongodbList).Union(rootconfig.RedisList).SingleOrDefault(item => item.Key == dbName).Value; var r = new Dictionary <string, List <List <long> > >(); if (c != null) { var db = server.GetDatabase(dbName); var colNames = db.GetCollectionNames().Where(name => !name.Contains("system.") && !name.Contains("$")); if (string.IsNullOrEmpty(aggName)) { colNames = colNames.Where(n => !n.Contains("__")).ToList(); } else { colNames = colNames.Where(n => n.Contains("__" + aggName)).ToList(); } Parallel.ForEach(colNames, colName => { var colKey = colName; if (colKey.Contains("__")) { colKey = colKey.Substring(0, colKey.IndexOf("__")); } if (c.ComponentItems.ContainsKey(colKey)) { var citem = c.ComponentItems[colKey]; if (string.IsNullOrEmpty(groupName) || groupName == citem.GroupName) { if (citem.ItemValueType != ItemValueType.TextValue) { var col = db.GetCollection(colName); var data = col.FindAll().SetLimit(pagesize).SetSkip(pageindex * pagesize) .SetSortOrder(SortBy.Descending("$natural")).ToList(); var v = data.Select(item => new List <long> { Convert.ToInt64((item["_id"].AsDateTime.ToLocalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds), Math.Max(Convert.ToInt64(item["V"].RawValue), 0), }).Reverse().ToList(); if (v.Count > 0 && !r.ContainsKey(citem.Name)) { lock (r) { r.Add(citem.Name, v); } } } } } }); } return(r.OrderBy(_ => _.Key).ToDictionary(_ => _.Key, _ => _.Value)); }
private void GetMetricValue() { if (DateTime.Now.Subtract(lastPoll).TotalSeconds > _pollingIntervalInSeconds) { _lastDelay = 0; var lastCommitDoc = _commitsCollection.FindAll() .SetSortOrder(SortBy.Descending("_id")) .SetFields(Fields.Include("_id")) .FirstOrDefault(); if (lastCommitDoc == null) { return; } var lastCommit = lastCommitDoc["_id"].AsInt64; //db.checkpoints.aggregate( //[ // {$match : {"Active": true}} // ,{$project : {"Slot" : 1, "Current" : 1}} // ,{$group : {"_id" : "$Slot", "Current" : {$min : "$Current"}}} //]) BsonDocument[] pipeline = { BsonDocument.Parse(@"{$match : {""Active"": true}}"), BsonDocument.Parse(@"{$project : {""Slot"" : 1, ""Current"" : 1}}"), BsonDocument.Parse(@"{$group : {""_id"" : ""$Slot"", ""Current"" : {$min : ""$Current""}}}") }; AggregateArgs args = new AggregateArgs(); args.Pipeline = pipeline; args.AllowDiskUse = true; //important for large file systems var allCheckpoints = _checkpointCollection.Aggregate(args); foreach (BsonDocument metric in allCheckpoints) { var slotName = metric["_id"].AsString; Int64 current; if (!metric["Current"].IsBsonNull) { current = Int64.Parse(metric["Current"].AsString); } else { current = 0; } var delay = lastCommit - current; if (delay > _lastDelay) { _lastDelay = delay; } _lastMetrics[slotName] = new SlotStatus(slotName, delay); } lastPoll = DateTime.Now; } }
public override ICollection <PersistentEvent> GetByProjectId(string projectId, PagingOptions paging = null, bool useCache = false, TimeSpan?expiresIn = null) { var pagingWithSorting = new PagingWithSortingOptions(paging) { SortBy = SortBy.Descending(FieldNames.Date_UTC) }; GetBeforeAndAfterQuery(pagingWithSorting); return(base.GetByProjectId(projectId, pagingWithSorting, useCache, expiresIn)); }
public MongoCursor <BsonDocument> GetCursorSorted(IMongoQuery _objectIdentifier) { //string _objectIdentifier. //BsonBinaryData id = new BsonBinaryData(_objectIdentifier.ToByteArray()); MongoCursor <BsonDocument> Cursor = MongoCollection.Find(_objectIdentifier).SetSortOrder(SortBy.Descending("PersistedDateTime")); return(Cursor); }
/////////////////////////////////////////////////////////////// // UPDATE FUNCTION ////////////////////////////////////////////////////////////// public static void updateLiteral(string WallId, string postval, string embedval) { MongoCollection <Wall> objCollection = db.GetCollection <Wall>("c_Wall"); var query = Query.EQ("_id", ObjectId.Parse(WallId)); var sortBy = SortBy.Descending("_id"); var update = Update.Set("Post", postval) .Set("EmbedPost", embedval); var result = objCollection.FindAndModify(query, sortBy, update, true); }
public IEnumerable <Content> GetContentDetails(int limit, int skip) { var contentCursor = this.MongoConnectionHandler.MongoCollection.FindAllAs <Content>() .SetSortOrder(SortBy <Content> .Descending(g => g.DateCreated)) .SetLimit(limit) .SetSkip(skip) .SetFields(Fields <Content> .Include(g => g.Id, g => g.Body, g => g.DateCreated, g => g.Title, g => g.Order)); return(contentCursor); }
public IEnumerable <Customer> GetAllCustomers(int limit, int skip) { var gamesCursor = this.MongoConnectionManager.MongoCollection.FindAllAs <Customer>() .SetSortOrder(SortBy <Customer> .Descending(g => g.CreatedDate)) .SetLimit(limit) .SetSkip(skip) .SetFields(Fields <Customer> .Include(g => g.Id, g => g.LastName, g => g.FirstName)); return(gamesCursor); }
public IEnumerable <Game> List(int limit, int skip) { var data = this.MongoCollectionHandler.MongoCollection.FindAllAs <Game>() .SetSortOrder(SortBy <Game> .Descending(m => m.ReleaseDate)) .SetLimit(limit) .SetSkip(skip) .SetFields(Fields <Game> .Include(m => m.Id, m => m.Name, m => m.ReleaseDate)); return(data); }