/// <summary> /// let the followerId follow the target id /// </summary> /// <param name="targetId">target(followee) profile id</param> /// <param name="followerId">the follower Profile Id</param> public void Follow(Guid targetId, Guid followerId) { //不允许自己follow自己 if (targetId == followerId) { throw new Exception("不允许自己follow自己"); } Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("_id", followerId); QueryObject <T> query = new QueryObject <T>(EntityRepository); query.AppendQuery(queryDict, QueryLogic.And); ((MongoDBRepository <T>)EntityRepository).Update(query, Update.AddToSet("FollowingIds", targetId)); //increase the followee's follower count Dictionary <string, object> queryDict2 = new Dictionary <string, object>(); queryDict2.Add("_id", targetId); QueryObject <T> query2 = new QueryObject <T>(EntityRepository); query2.AppendQuery(queryDict2, QueryLogic.And); ((MongoDBRepository <T>)EntityRepository).Update(query2, Update.Inc("FollowerCount", 1)); //产生用户start follow事件 EventService.Publish("StartFollowingEvent", targetId, followerId); }
public void TestAddToSetTwice() { var update = Update.AddToSet("a", 1).AddToSet("b", 2); var expected = "{ \"$addToSet\" : { \"a\" : 1, \"b\" : 2 } }"; Assert.Equal(expected, update.ToJson()); }
public void TestAddToSet() { var update = Update.AddToSet("name", "abc"); var expected = "{ \"$addToSet\" : { \"name\" : \"abc\" } }"; Assert.Equal(expected, update.ToJson()); }
public void TestAddToSet_Typed() { var update = Update <Test> .AddToSet(t => t.Y, 1); var expected = "{ \"$addToSet\" : { \"y\" : 1 } }"; Assert.Equal(expected, update.ToJson()); }
public Task CleanupAsync(Guid id) { return(Collection.UpdateManyAsync( Filter.And( Filter.AnyEq(x => x.ReferencedIds, id), Filter.AnyNe(x => x.ReferencedIdsDeleted, id)), Update.AddToSet(x => x.ReferencedIdsDeleted, id))); }
protected Task On(ContentDeleted @event) { return(Collection.UpdateManyAsync( Filter.And( Filter.AnyEq(x => x.ReferencedIds, @event.ContentId), Filter.AnyNe(x => x.ReferencedIdsDeleted, @event.ContentId)), Update.AddToSet(x => x.ReferencedIdsDeleted, @event.ContentId))); }
public void UpdateFor(List <string> airingIds, List <string> tasks) { var filter = Query.In("AssetId", new BsonArray(airingIds)); foreach (var task in tasks) { _currentAirings.Update(filter, Update.AddToSet("Tasks", task), UpdateFlags.Multi); } }
public Task AddFollowerAsync(string userId, FollowerEntity follower) { return(Task.Run(() => { IMongoQuery query = Query <UserEntity> .EQ(entity => entity.Id, userId); UpdateBuilder <UserEntity> update = Update <UserEntity> .AddToSet(entity => entity.Followers, follower); Collection.Update(query, update); })); }
public Task AddMembershipAsync(string userId, UserMembershipEntity membership) { return(Task.Run(() => { IMongoQuery query = Query <UserEntity> .EQ(entity => entity.Id, userId); UpdateBuilder <UserEntity> update = Update <UserEntity> .AddToSet(entity => entity.Memberships, membership); Collection.Update(query, update); })); }
public void AddToWatchlist(string userId, int movieId) { //var usersCollection = _database.GetCollection<ApplicationUser>("AspNetUsers"); var query = Query <ApplicationUser> .EQ(user => user.Id, userId); var update = Update <ApplicationUser> .AddToSet(user => user.Watchlist, movieId); _usersCollection.Update(query, update); }
public void Subscribe(Address client, IEnumerable <MessageType> messageTypes) { foreach (var key in GetMessageTypeKeys(messageTypes)) { var query = Query <Subscription> .EQ(s => s.Id, key); var update = Update <Subscription> .AddToSet(s => s.Subscribers, client.ToString()); _subscriptions.Update(query, update, UpdateFlags.Upsert); } }
protected Task On(AssetDeleted @event, EnvelopeHeaders headers) { return(ForAppIdAsync(@event.AppId.Id, collection => { return collection.UpdateManyAsync( Filter.And( Filter.AnyEq(x => x.ReferencedIds, @event.AssetId), Filter.AnyNe(x => x.ReferencedIdsDeleted, @event.AssetId)), Update.AddToSet(x => x.ReferencedIdsDeleted, @event.AssetId)); })); }
public void Store(Type messageType, string subscriberInputQueue) { var collection = database.GetCollection(collectionName); var criteria = Query.EQ("_id", messageType.FullName); var update = Update.AddToSet("endpoints", subscriberInputQueue); var safeModeResult = collection.Update(criteria, update, UpdateFlags.Upsert, SafeMode.True); EnsureResultIsGood(safeModeResult, "Adding {0} to {1} where _id is {2}", subscriberInputQueue, collectionName, messageType.FullName); }
public Project AddUser(ObjectId projectId, User user) { Collection.FindAndModify(new FindAndModifyArgs { Query = Query <Project> .Where(p => p.Id == projectId), Update = Update <Project> .AddToSet(p => p.Users, user) }); var project = FindById(projectId); Sync(new SyncEventArgs <IEntity>("save", project)); return(project); }
public Team AddUser(ObjectId teamId, User user) { Collection.FindAndModify(new FindAndModifyArgs { Query = Query <Team> .Where(t => t.Id == teamId), Update = Update <Team> .AddToSet(t => t.Users, user) }); var team = FindById(teamId); Sync(new SyncEventArgs <IEntity>("save", team)); return(team); }
public void TestAddToSetEach() { var server = Configuration.TestServer; var database = Configuration.TestDatabase; var collection = Configuration.GetTestCollection <C>(); collection.RemoveAll(); var c = new C { InnerObjects = new List <D>() }; collection.Insert(c); var id = c.Id; var query = Query.EQ("_id", id); var update = Update.AddToSet("InnerObjects", 1); collection.Update(query, update); var d1 = new D { X = 1 }; update = Update.AddToSetWrapped("InnerObjects", d1); collection.Update(query, update); var d2 = new D { X = 2 }; var d3 = new D { X = 3 }; update = Update.AddToSetEachWrapped("InnerObjects", d1, d2, d3); collection.Update(query, update); var document = collection.FindOneAs <BsonDocument>(); var json = document.ToJson(); string expected; if (server.BuildInfo.Version >= new Version(2, 6, 0)) { expected = "{ '_id' : ObjectId('#ID'), 'InnerObjects' : [1, { 'X' : 1 }, { 'X' : 2 }, { 'X' : 3 }] }"; } else { // prior to version 2.5.2 the server would reorder the elements when Update was used expected = "{ 'InnerObjects' : [1, { 'X' : 1 }, { 'X' : 2 }, { 'X' : 3 }], '_id' : ObjectId('#ID') }"; } expected = expected.Replace("#ID", id.ToString()); expected = expected.Replace("'", "\""); Assert.AreEqual(expected, json); }
protected Task On(ContentDeleted @event, EnvelopeHeaders headers) { return(ForAppIdAsync(@event.AppId.Id, async collection => { await collection.UpdateManyAsync( Filter.And( Filter.AnyEq(x => x.ReferencedIds, @event.ContentId), Filter.AnyNe(x => x.ReferencedIdsDeleted, @event.ContentId)), Update.AddToSet(x => x.ReferencedIdsDeleted, @event.ContentId)); await collection.DeleteOneAsync(x => x.Id == headers.AggregateId()); })); }
public QueryBuilder <T> UpdateAddToSet <F>(Expression <Func <T, IEnumerable <F> > > collection, F value) { if (Update == null) { Update = UpdateBuilder.AddToSet(collection, value); } else { Update = Update.AddToSet(collection, value); } return(this); }
public void AddToWatchList(int userId, string watchedUser) { IMongoQuery query = Query.EQ("UserId", userId); IMongoUpdate update = Update.AddToSet("WatchList", watchedUser); MongoCollection <ManologyUser> usersCollection = DB.GetCollection <ManologyUser>("Users"); var cursor = usersCollection.FindOne(query); if (cursor.WatchList.Count >= 10) { usersCollection.Update(query, Update.Pull("WatchList", cursor.WatchList[0])); } usersCollection.Update(query, update, UpdateFlags.Upsert); }
public Idea VoteDown(ObjectId id, ObjectId userId) { Collection.FindAndModify(new FindAndModifyArgs { Query = Query <Idea> .Where(i => i.Id == id), Update = Update <Idea> .AddToSet(i => i.UsersDown, userId) .Pull(i => i.UsersUp, userId) }); var idea = FindById(id); Sync(new SyncEventArgs <IEntity>("save", idea)); return(idea); }
public async Task <ChecklistTask> AddChecklistTask(AddChecklistTaskRequest request) { var task = new ChecklistTask() { Order = request.Order, Id = ObjectId.GenerateNewId().ToString(), Text = request.Text }; var update = Update.AddToSet(x => x.ChecklistTasks, task); var filter = Filter.Eq(x => x.Id, request.ChecklistId); await Collection.UpdateOneAsync(filter, update); return(task); }
public async Task AddChecklistToUser(string checklistsId, Auth requestAuth, bool isOwned) { var user = await GetUser(requestAuth); var update = Update.AddToSet(x => x.Checklists, new UsersChecklist { ChecklistId = checklistsId, Order = user.Checklists.Max(y => y.Order) + 1, IsOwned = isOwned }); var filter = Filter.Eq(x => x.Email, requestAuth.Email); await Collection.UpdateOneAsync(filter, update); }
public void Handle(CommentApproved @event) { var collection = CreateCollection(); var postsRepository = new PostsRepository(_mongoDatabase); var post = postsRepository.Find(@event.AggregateRootId); var comment = post.Comments.First(x => x.Id == @event.CommentId); var find = Query.EQ("_id", @event.AggregateRootId); var update = Update.AddToSet("Comments", comment.ToBsonDocument()); collection.Update(find, update); }
public void InsertHug(string recipient, Hug hug) { var mongUserObject = _mongoCollection.AsQueryable().Single(a => a.UserID == new BsonObjectId(recipient)); var hugs = mongUserObject.Hugs; if (hugs.Any(a => a.SenderID == hug.SenderID)) //No reason to store this - the user has already hugged. { return; } hugs.Add(hug); var query = Query.EQ("_id", new BsonObjectId(recipient)); var update = Update.AddToSet("Hugs", hug.ToBsonDocument()); _mongoCollection.FindAndModify(query, SortBy.Null, update); }
public void TestAddToSetEach() { var server = Configuration.TestServer; var database = Configuration.TestDatabase; var collection = Configuration.GetTestCollection <C>(); collection.RemoveAll(); var c = new C { InnerObjects = new List <D>() }; collection.Insert(c); var id = c.Id; var query = Query.EQ("_id", id); var update = Update.AddToSet("InnerObjects", 1); collection.Update(query, update); var d1 = new D { X = 1 }; update = Update.AddToSetWrapped("InnerObjects", d1); collection.Update(query, update); var d2 = new D { X = 2 }; var d3 = new D { X = 3 }; update = Update.AddToSetEachWrapped("InnerObjects", d1, d2, d3); collection.Update(query, update); var document = collection.FindOneAs <BsonDocument>(); var json = document.ToJson(); var expected = "{ 'InnerObjects' : [1, { 'X' : 1 }, { 'X' : 2 }, { 'X' : 3 }], '_id' : ObjectId('#ID') }"; // server put _id at end? expected = expected.Replace("#ID", id.ToString()); expected = expected.Replace("'", "\""); Assert.AreEqual(expected, json); }
//update = Update<MongoProductView>.AddToSet<string>(item => item.Keywords.AsEnumerable(), new string[] { "test" }); private static void UpdateDocumentsWithNewKeyword() { var array = new List <string>() { "new" }; var query = Query <MongoProductView> .All(item => item.Keywords, array); //show that we did return a product. var found = Collections.ProductViewCollection.Find(query).ToList(); //Add keyword to all documents that have a keyword of new var update = Update.AddToSet("keywords", "test"); //you could also use push if you wanted it added no matter what. //var update = Update.Push("keywords", "test"); Collections.ProductViewCollection.Update(query, update); Console.WriteLine(""); }
public void TestAddToSetEach() { var server = MongoServer.Create("mongodb://localhost/?safe=true"); var database = server["onlinetests"]; var collection = database.GetCollection <C>("csharp111"); collection.RemoveAll(); var c = new C { InnerObjects = new List <D>() }; collection.Insert(c); var id = c.Id; var query = Query.EQ("_id", id); var update = Update.AddToSet("InnerObjects", 1); collection.Update(query, update); var d1 = new D { X = 1 }; update = Update.AddToSetWrapped("InnerObjects", d1); collection.Update(query, update); var d2 = new D { X = 2 }; var d3 = new D { X = 3 }; update = Update.AddToSetEachWrapped("InnerObjects", d1, d2, d3); collection.Update(query, update); var document = collection.FindOneAs <BsonDocument>(); var json = document.ToJson(); var expected = "{ 'InnerObjects' : [1, { 'X' : 1 }, { 'X' : 2 }, { 'X' : 3 }], '_id' : { '$oid' : '#ID' } }"; // server put _id at end? expected = expected.Replace("#ID", id.ToString()); expected = expected.Replace("'", "\""); Assert.AreEqual(expected, json); }
/// <summary> /// Registers the video file by media identifier. 'contents.name' is considered unique. If it /// exist, update, else insert /// </summary> /// <param name="file">The file.</param> /// <param name="user">The user.</param> void RegisterVideoFileByMediaId(Model.File file, string userName) { // Gather audit information file.ModifiedDatetime = DateTime.UtcNow; file.ModifiedBy = userName; // Check if file exist for given media id. If not, insert new file document, else; // if it exist, verify if the sub document matches. If so, update // existing sub document, else insert new sub document MongoCollection <Model.File> fileCollection = _database.GetCollection <Model.File>("File"); var query = Query.And(Query.EQ("MediaId", file.MediaId), Query.NotExists("AiringId")); Model.File dbFile = fileCollection.Find(query).FirstOrDefault(); if (dbFile == null) { // Add new file document fileCollection.Save(file); } else { // This removes existing content if it exists and then inserts. foreach (var content in file.Contents) { query = Query.And( Query.EQ("MediaId", file.MediaId), Query.NotExists("AiringId"), Query.EQ("Contents.Name", content.Name)); // Remove, if it exist var pull = Update <Model.File> .Pull(x => x.Contents, builder => builder.EQ(q => q.Name, content.Name)); fileCollection.Update(query, pull); // Insert query = Query.And(Query.EQ("MediaId", file.MediaId), Query.NotExists("AiringId")); fileCollection.Update(query, Update <Model.File> .AddToSet(c => c.Contents, content) .Set(c => c.ModifiedBy, file.ModifiedBy) .Set(c => c.ModifiedDatetime, file.ModifiedDatetime)); } } }
/// <summary> /// Send a friend request /// </summary> /// <param name="userName"></param> /// <returns></returns> public JsonResult SendFriendRequest(string userName) { _dbContext = new MongoContext(); var userId = Session["User"]; Users user = _dbContext.database.GetCollection <Users>("users").FindOne(Query.EQ("_id", (ObjectId)userId)); if (user != null) { Users userToAsk = _dbContext.database.GetCollection <Users>("users").FindOne(Query.EQ("UserName", userName)); //userToAsk.PendingFriendsRequest.Add(user._id); //Ajout de l'id dans notre pending friend request et dans celle de l'utilisateur concernée _dbContext.database.GetCollection <Users>("users").FindAndModify(Query.EQ("_id", userToAsk._id), null, Update.AddToSet("PendingFriendsRequest", user._id)); _dbContext.database.GetCollection <Users>("users").FindAndModify(Query.EQ("_id", user._id), null, Update.AddToSet("PendingFriendsRequest", userToAsk._id)); return(Json(true, JsonRequestBehavior.AllowGet)); } return(Json(false, JsonRequestBehavior.AllowGet)); }
public void Persist <T>(Guid trackingNumber, T @event) where T : RoutingSlipEventDocument { IMongoQuery upsertQuery = Query <RoutingSlipDocument> .EQ(x => x.TrackingNumber, trackingNumber); WriteConcernResult result = _collection.Update(upsertQuery, Update <RoutingSlipDocument> .AddToSet(x => x.Events, @event), UpdateFlags.Upsert); if (result.Ok == false || result.DocumentsAffected != 1) { throw new SaveEventException(trackingNumber, "Failed to save the event"); } // if this was the first save, this will be false if (result.UpdatedExisting == false) { if (_log.IsDebugEnabled) { _log.DebugFormat("{0} {1}", trackingNumber, typeof(T).Name); } } }