private static UpdateDefinition <TEntity> CreateFromDiff <TEntity>(UpdateDefinition <TEntity> definition, string name, BsonValue valueA, BsonValue valueB) where TEntity : class { if (valueB == null) { return(definition.Set(name, BsonNull.Value)); } else if (valueA?.BsonType != valueB?.BsonType) { return(definition.Set(name, valueB)); } var bsonType = valueA?.BsonType; if (bsonType == BsonType.Array) { return(CreateFromDiff(definition, name, valueA.AsBsonArray, valueB.AsBsonArray)); } else if (bsonType == BsonType.Document) { return(CreateFromDiff(definition, name, valueA.AsBsonDocument, valueB.AsBsonDocument)); } else if (valueA != valueB) { return(definition.Set(name, valueB)); } return(definition); }
public async Task <bool> UpdateUserAsync(FilterDefinition <BsonDocument> filter, UpdateUserInfo updateUser) { try { UpdateDefinition <BsonDocument> update = Builders <BsonDocument> .Update.Set("updateAt", BsonDateTime.Create(DateTime.Now)); if (updateUser.username != null) { FilterDefinition <BsonDocument> nameFilter = Builders <BsonDocument> .Filter.Eq("username", updateUser.username); BsonDocument checkUser = await mCollection.Find(nameFilter).FirstAsync(); if (checkUser != null) { return(false); } update = update.Set("username", updateUser.username); } if (updateUser.password != null) { string newPassword = Utilities.CalcuteSHA256Hash(updateUser.password); update = update.Set("password", newPassword); } if (updateUser.email != null) { update = update.Set("email", updateUser.email); } UpdateResult result = mCollection.UpdateOne(filter, update); return(result.ModifiedCount > 0); } catch { return(false); } }
public async Task <User> RecordUser(UserInfo userInfo) { UpdateDefinition <User> update = Builders <User> .Update .Set(u => u.TwitchDisplayName, userInfo.TwitchDisplayName) .Set(u => u.SimpleName, userInfo.SimpleName) .Set(u => u.LastActiveAt, userInfo.UpdatedAt); if (userInfo.Color != null) { update = update.Set(u => u.Color, userInfo.Color.StringWithoutHash); } if (userInfo.FromMessage) { update = update.Set(u => u.LastMessageAt, userInfo.UpdatedAt); } async Task <User?> UpdateExistingUser() => await Collection.FindOneAndUpdateAsync <User>( filter : u => u.Id == userInfo.Id, update : update, options : new FindOneAndUpdateOptions <User> { ReturnDocument = ReturnDocument.After, IsUpsert = false } ); User?user = await UpdateExistingUser(); if (user != null) { return(user); } // user doesn't exist yet! user = new User( id: userInfo.Id, name: userInfo.SimpleName, twitchDisplayName: userInfo.TwitchDisplayName, simpleName: userInfo.SimpleName, color: userInfo.Color?.StringWithoutHash, firstActiveAt: userInfo.UpdatedAt, lastActiveAt: userInfo.UpdatedAt, lastMessageAt: userInfo.FromMessage ? userInfo.UpdatedAt : (Instant?)null, pokeyen: _startingPokeyen, tokens: _startingTokens ); try { await Collection.InsertOneAsync(document : user); } catch (MongoWriteException ex) when(ex.WriteError.Category == ServerErrorCategory.DuplicateKey) { // oops, race condition! // Someone inserted the user after our check but before our insertion call just now. // Since it exists now, just re-attempt updating the existing entry. user = await UpdateExistingUser() ?? throw new InvalidOperationException($"user {userInfo.SimpleName} must exist now!"); } return(user); }
private static UpdateDefinition <TDocument> GetUpdatePartialUpdateDefinition(object updateObject) { var updateProperties = updateObject.GetType().GetRuntimeProperties(); var updateBuilder = Builders <TDocument> .Update; UpdateDefinition <TDocument> updateDefinition = null; foreach (var propertyInfo in updateProperties) { var value = propertyInfo.GetValue(updateObject); if (value is Array || value is ICollection || value is IList) { //Collections are not supported throw new NotImplementedException("Collections are not supported"); } var fullName = propertyInfo.Name.Replace('_', '.'); var propertyTree = fullName.Split('.'); PropertyInfo currentProperty = null; for (var treeDepthIndex = 0; treeDepthIndex < propertyTree.Count(); treeDepthIndex++) { if (currentProperty == null) { if (!TryGetPropertyInfo(typeof(TDocument), propertyTree[treeDepthIndex], out currentProperty)) { throw new Exception("No matching property found for the partial update."); } } else { if (!TryGetPropertyInfo(currentProperty.GetType(), propertyTree[treeDepthIndex], out currentProperty)) { throw new Exception("No matching property found for the partial update."); } } } if (updateDefinition == null) { updateDefinition = updateBuilder.Set(fullName, value); } else { updateDefinition = updateDefinition.Set(fullName, value); } } bool TryGetPropertyInfo(Type parentType, string propertyName, out PropertyInfo propertyInfo) { var documentPropertyNames = parentType.GetRuntimeProperties().ToList(); propertyInfo = documentPropertyNames.FirstOrDefault(m => m.Name == propertyName); return(propertyInfo != null); } updateDefinition = updateDefinition.Set(x => x.UpdatedAtUtc, DateTime.UtcNow); return(updateDefinition); }
/// <summary> /// Updates partially (only the provided properties) an <see cref="TEntity"/>. /// </summary> /// <param name="id">The if of the <see cref="TEntity"/>.</param> /// <param name="elmIn">The new data of the <see cref="TEntity"/>.</param> /// <returns>The operation result.</returns> public virtual UpdateResult UpdatePartially(Guid id, TEntity elmIn) { string jsonValue = JsonSerializer.Serialize(elmIn); var changesDocument = BsonDocument.Parse(jsonValue); var filter = Builders <TEntity> .Filter.Eq("_id", id); UpdateDefinition <TEntity> update = null; foreach (var change in changesDocument) { if (update == null) { var builder = Builders <TEntity> .Update; update = builder.Set(change.Name, change.Value); } else { update = update.Set(change.Name, change.Value); } } /* Following 3 lines are for debugging purposes only * var registry = BsonSerializer.SerializerRegistry; * var serializer = registry.GetSerializer<BsonDocument>(); * var rendered = update.Render(serializer, registry).ToJson(); */ return(this.Entities.UpdateOne(filter, update)); }
private static UpdateDefinition <TEntity> CreateFromDiff <TEntity>(UpdateDefinition <TEntity> definition, string name, BsonArray arrayA, BsonArray arrayB) where TEntity : class { var arrayACount = arrayA.Count; var arrayBCount = arrayB.Count; //Due to limitations of MongoDB, we can't pull/push at the same time. //As highlighted on task SERVER-1014 (MongoDB Jira), you can't pull at an index, only at a value match. //You could avoid the pull by simply pop-ing items off the list for the length difference between "arrayA" and "arrayB". //That said, we can't run "conflicting" updates on the same path (eg. pull and push) at the same time. //Instead, if the arrays are the same length, we check differences per index. //If the arrays are different lengths, we set the whole array in the update. if (arrayACount == arrayBCount) { for (int i = 0, l = arrayBCount; i < l; i++) { var fullName = name + "." + i; definition = CreateFromDiff(definition, fullName, arrayA[i], arrayB[i]); } } else { definition = definition.Set(name, arrayB); } return(definition); }
private static UpdateDefinition <TEntity> CreateFromDiff <TEntity>(UpdateDefinition <TEntity> definition, string name, BsonDocument documentA, BsonDocument documentB) where TEntity : class { var documentAProperties = documentA?.Names ?? Enumerable.Empty <string>(); var documentBProperties = documentB?.Names ?? Enumerable.Empty <string>(); var propertyNames = documentAProperties.Union(documentBProperties); if (name != string.Empty) { name += "."; } foreach (var propertyName in propertyNames) { var fullName = name + propertyName; if (documentB == null || !documentB.Contains(propertyName)) { definition = definition.Unset(new StringFieldDefinition <TEntity>(fullName)); } else if (documentA == null || !documentA.Contains(propertyName)) { definition = definition.Set(fullName, documentB[propertyName]); } else { definition = CreateFromDiff(definition, fullName, documentA[propertyName], documentB[propertyName]); } } return(definition); }
public async Task Update <T>(string collectionName, string id, T record) where T : BaseMongoEntity { var collection = this.db.GetCollection <T>(collectionName); var filterDef = Builders <T> .Filter.Eq(entry => entry.Id, id); var updateDefBuilder = Builders <T> .Update; UpdateDefinition <T> updateDef = null; foreach (var prop in record.GetType().GetProperties()) { if (prop.Name == "Id" || prop.GetValue(record) == null) { continue; } if (updateDef != null) { updateDef = updateDef.Set(prop.Name, prop.GetValue(record)); } else { updateDef = updateDefBuilder.Set(prop.Name, prop.GetValue(record)); } } var updateResult = await collection.UpdateManyAsync(filterDef, updateDef); if (!updateResult.IsAcknowledged) { throw new Exception("Update failed"); } }
///////////////////////////////////////// // remove client from business ///////////////////////////////////////// public async Task <Boolean> removeFromBusiness(string businessName, string client, bool block) { var builderF = Builders <Business> .Filter; FilterDefinition <Business> filter = builderF.Eq("BName", businessName); var builderU = Builders <Business> .Update; UpdateDefinition <Business> update = builderU.Pull("BClient", client); // refers to blocked list if (block) { var tempResult = await _businesses.Find(filter).FirstOrDefaultAsync(); if (tempResult.BBlockedList.Length <= 0 || tempResult.BBlockedList[0] == null) { string[] blocked = new string[] { client }; update = update.Set("BBlockedList", blocked); } else { update = update.Push("BBlockedList", client); } } var result = await _businesses.UpdateOneAsync(filter, update); return(result != null ? true : false); }
protected UpdateDefinition <TDocument> AddUpdateProperties <TDocument>(UpdateDefinition <TDocument> update, string modifiedBy) where TDocument : IBaseModel { update = update.Set(x => x.ModifiedOn, DateTime.UtcNow) .Set(x => x.ModifiedBy, modifiedBy); return(update); }
public UpdateDefinition <BsonDocument> BuildUpdatesForSave(UpdateDefinition <BsonDocument> update, TrackableDictionaryTracker <TKey, TValue> tracker, params object[] keyValues) { var keyNamespace = DocumentHelper.ToDotPathWithTrailer(keyValues); foreach (var change in tracker.ChangeMap) { switch (change.Value.Operation) { case TrackableDictionaryOperation.Add: case TrackableDictionaryOperation.Modify: update = update == null ? Builders <BsonDocument> .Update.Set(keyNamespace + change.Key, change.Value.NewValue) : update.Set(keyNamespace + change.Key, change.Value.NewValue); break; case TrackableDictionaryOperation.Remove: update = update == null ? Builders <BsonDocument> .Update.Unset(keyNamespace + change.Key) : update.Unset(keyNamespace + change.Key); break; } } return(update); }
public static void UpdateOrInsert <T>(this IMongoCollection <T> collection, T prototype, UpdateOptions options = null) { if (options == null) { options = new UpdateOptions { IsUpsert = true }; } var doc = new BsonDocument(); var wr = new BsonDocumentWriter(doc); BsonSerializer.Serialize(wr, prototype); var update = Builders <T> .Update; UpdateDefinition <T> definition = null; foreach (var el in doc) { if (el.Name != IdName) { definition = definition == null?update.Set(el.Name, el.Value) : definition.Set(el.Name, el.Value); } } collection.UpdateOne(Builders <T> .Filter.Eq(IdName, doc[IdName]), definition, options); }
//Actualiza en la base de datos public override void update(String table, List <Tuple <String, Object> > pks, List <Tuple <String, Object> > fields) { var mongoColl = getCollection(table); if (pks.Count < 1) { new GeneralORMException("There is no primary keys asociated with the mongoDB update operation"); } var filter = Builders <dynamic> .Filter.Eq(pks[0].Item1, pks[0].Item2); for (int i = 1; i < pks.Count; i++) { Tuple <String, Object> pk = pks[i]; filter = filter & Builders <dynamic> .Filter.Eq(pks[i].Item1, pks[i].Item2); } UpdateDefinition <dynamic> updateFields = null; if (fields.Count > 0) { updateFields = Builders <dynamic> .Update.Set(fields[0].Item1, fields[0].Item2); for (int i = 1; i < fields.Count; i++) { Tuple <String, Object> field = fields[i]; updateFields = updateFields.Set(field.Item1, field.Item2); } } if (fields.Count > 0) { mongoColl.UpdateOne(filter, updateFields); } }
///////////////////////////////////////////// /// updating user from db /////////////////////////////////// public async Task <bool> updateUserFromDB(User user) { FilterDefinition <User> filter = Builders <User> .Filter.Eq("Email", user.Email); UpdateDefinition <User> update = null; bool flag = false; foreach (var field in user.GetType().GetProperties()) { if (field.GetValue(user) != null && !field.GetValue(user). Equals("") && !field.Name.Equals("Type")) { if (flag == false) { update = Builders <User> .Update.Set(field.Name, field.GetValue(user)); flag = true; } else { update = update.Set(field.Name, field.GetValue(user)); } } } UpdateResult result = await _users.UpdateOneAsync(filter, update); if (result.MatchedCount != result.ModifiedCount) { return(false); } return(true); }
protected async Task <long> SetAsync(FilterDefinition <TEntity> filter, UpdateDefinition <TEntity> update, UpdateOptions options = null) { var result = await Collection.UpdateManyAsync(filter, update.Set(v => v.ModifiedAt, DateTime.UtcNow), options).ConfigureAwait(false); return(result.ModifiedCount + (result.UpsertedId != null ? 1 : 0)); }
public int Update <TEntity>(TEntity entity) where TEntity : class, IEntity { UpdateDefinition <TEntity> update = null; PropertyInfo[] props = entity.GetType().GetProperties(); foreach (PropertyInfo prop in props) { if (prop.GetValue(entity, null) != null) { if (update == null) { update = Builders <TEntity> .Update.Set(prop.Name, prop.GetValue(entity, null)); } else { update.Set(prop.Name, prop.GetValue(entity, null)); } } } if (update != null) { MongodbHelper.Default.GetCollection <TEntity>() .UpdateOne(new ExpressionFilterDefinition <TEntity>(x => x.Id == entity.Id), update); } return(1); }
/// <inheritdoc/> public virtual async ValueTask UpDateAsync(FilterDefinition <T> filter, UpdateDefinition <T> updateDefinition, bool updateTime = true) { if (updateTime) { updateDefinition = updateDefinition.Set(t => t.UpdateTime, DateTime.UtcNow); } await collection.UpdateManyAsync(filter, updateDefinition); }
/// <inheritdoc/> public virtual async ValueTask UpDateAsync(Guid id, UpdateDefinition <T> updateDefinition, bool updateTime = true) { if (updateTime) { updateDefinition = updateDefinition.Set(t => t.UpdateTime, DateTime.UtcNow); } var re = await collection.UpdateOneAsync(t => t.Id == id, updateDefinition); }
/// <summary> /// Update the workflow. The only things that can be updated are name and description /// </summary> /// <param name="id"></param> /// <param name="version"></param> /// <param name="action"></param> /// <exception cref="NotImplementedException"></exception> public void Update(Guid id, int version, Action <ProcessDefinitionPersistenceBase> action, AccountData[] accounts = null) { UpdateProcessDefPersistence u = new UpdateProcessDefPersistence(); action(u); var filter = Builders <ProcessDefinitionPersistence> .Filter.And( Builders <ProcessDefinitionPersistence> .Filter.Eq(r => r.Id, id), Builders <ProcessDefinitionPersistence> .Filter.Eq(r => r.Version, version) ); UpdateDefinition <ProcessDefinitionPersistence> updatedef = null; if (u.NameSet) { updatedef = Builders <ProcessDefinitionPersistence> .Update.Set(r => r.Name, u.Name); } if (u.DescriptionSet) { if (updatedef == null) { updatedef = Builders <ProcessDefinitionPersistence> .Update.Set(r => r.Description, u.Description); } else { updatedef.Set(r => r.Description, u.Description); } } if (accounts != null) { if (updatedef == null) { updatedef = Builders <ProcessDefinitionPersistence> .Update.Set(r => r.Accounts, new List <AccountData>(accounts)); } else { updatedef.Set(r => r.Accounts, new List <AccountData>(accounts)); } } updatedef = updatedef?.CurrentDate(r => r.LastModified); if (updatedef == null) { return; } _collection.FindOneAndUpdate(filter, updatedef); }
public async Task UpdateOneById() { UpdateDefinition<UserModel> updateDocument = Builders<UserModel>.Update.Set(t => t.FirstName, "Update ratomir"); updateDocument = updateDocument.Set(t => t.LastName, "Pokemoni"); bool result = await _repository.UpdateOneAsync(Client, "5a6f01634d079623b07fa5af", updateDocument); Assert.True(result); }
/// <summary> /// Builds the update for a MongoDb field. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="updates">The updates.</param> /// <param name="field">The MongoDb field.</param> /// <param name="value">The value.</param> /// <returns>The update definition.</returns> public static UpdateDefinition <T> BuildUpdate <T>(UpdateDefinition <T> updates, string field, object value) { if (updates == null) { return(Builders <T> .Update.Set(field, value)); } return(updates.Set(field, value)); }
public async Task <Player> Modify(Guid id, ModifiedPlayer player) { // Update, 2 documents, {$set : {querydoc}} Player modPlayer = new Player(); UpdateDefinition <Player> updateList = Builders <Player> .Update.Set("_id", id); FilterDefinition <Player> filter = Builders <Player> .Filter.Eq("_id", id); bool done = false; modPlayer.Id = id; if (player.Score != null) { modPlayer.Score = (int)player.Score; updateList.Set("Score", modPlayer.Score); // DOESN'T WORK UpdateResult result = await Collection.UpdateOneAsync(filter, Builders <Player> .Update.Set("Score", modPlayer.Score)); if (result.IsAcknowledged) { done = true; } } if (player.Level != null) { modPlayer.Level = (int)player.Level; UpdateResult result = await Collection.UpdateOneAsync(filter, Builders <Player> .Update.Set("Level", modPlayer.Level)); if (result.IsAcknowledged) { done = true; } } if (player.Tags != null) { modPlayer.TagList = new List <PlayerTag>(); foreach (PlayerTag tag in player.Tags) { modPlayer.TagList.Add(tag); } UpdateResult result = await Collection.UpdateOneAsync(filter, Builders <Player> .Update.Set("TagList", modPlayer.TagList)); if (result.IsAcknowledged) { done = true; } } //UpdateResult result = await Collection.UpdateOneAsync(filter, updateList); if (done) { return(await Get(id)); } else { throw new InvalidPlayerIDException(id.ToString()); } }
public UpdateDefinition <BsonDocument> BuildUpdatesForCreate( UpdateDefinition <BsonDocument> update, IList <T> list, params object[] keyValues) { var valuePath = DocumentHelper.ToDotPath(keyValues); var bson = ConvertToBsonArray(list); return(update == null ? Builders <BsonDocument> .Update.Set(valuePath, bson) : update.Set(valuePath, bson)); }
/// <summary> /// 更新单条(自动更新UpdateTime字段) /// </summary> /// <typeparam name="T">文档类型</typeparam> /// <param name="collection">集合</param> /// <param name="filter">过滤器</param> /// <param name="update">更新定义</param> /// <param name="options">更新操作设置</param> /// <param name="cancellationToken">取消操作设置</param> /// <returns></returns> public static UpdateResult WhereUpdateOne <T>( this IMongoCollection <T> collection, FilterDefinition <T> filter, UpdateDefinition <T> update, UpdateOptions options = null, CancellationToken cancellationToken = default) where T : BaseMongoEntity { return(collection.UpdateOne(filter, update.Set(s => s.UpdateTime, DateTime.Now), options, cancellationToken)); }
/// <summary> /// 查询更新单条(自动更新UpdateTime字段) /// </summary> /// <typeparam name="T">文档类型</typeparam> /// <param name="collection">集合</param> /// <param name="filter">Lambda过滤器</param> /// <param name="update">更新定义</param> /// <param name="options">更新操作设置</param> /// <param name="cancellationToken">取消操作设置</param> /// <returns></returns> public static T FindOneAndUpdateOne <T>( this IMongoCollection <T> collection, Expression <Func <T, bool> > filter, UpdateDefinition <T> update, FindOneAndUpdateOptions <T, T> options = null, CancellationToken cancellationToken = default) where T : BaseMongoEntity { return(collection.FindOneAndUpdate(filter, update.Set(s => s.UpdateTime, DateTime.Now), options, cancellationToken)); }
/// <summary> /// 查询更新单条(自动更新UpdateTime字段) /// </summary> /// <typeparam name="T">文档类型</typeparam> /// <param name="collection">集合</param> /// <param name="id">文档默认ID</param> /// <param name="update">更新定义</param> /// <param name="options">更新操作设置</param> /// <param name="cancellationToken">取消操作设置</param> /// <returns></returns> public static T FindOneAndUpdateOne <T>( this IMongoCollection <T> collection, string id, UpdateDefinition <T> update, FindOneAndUpdateOptions <T, T> options = null, CancellationToken cancellationToken = default) where T : BaseMongoEntity { return(collection.FindOneAndUpdate <T, T>(f => f.Id == id, update.Set(s => s.UpdateTime, DateTime.Now), options, cancellationToken)); }
protected UpdateDefinition <TDocument> AddUpdateProperties <TDocument>(UpdateDefinition <TDocument> update, string modifiedBy) where TDocument : IBaseModel { if (!string.IsNullOrWhiteSpace(modifiedBy)) { update = update.Set(x => x.ModifiedOn, DateTime.UtcNow) .Set(x => x.ModifiedOnInt, ConvertDateTimeToInt(DateTime.UtcNow)) .Set(x => x.ModifiedBy, modifiedBy); } return(update); }
/// <summary> /// 更新单条(自动更新UpdateTime字段) /// </summary> /// <typeparam name="T">文档类型</typeparam> /// <param name="filter">过滤器</param> /// <param name="update">更新定义</param> /// <param name="options">更新操作设置</param> /// <param name="cancellationToken">取消操作设置</param> /// <returns></returns> public UpdateResult WhereUpdateOne <T>( FilterDefinition <T> filter, UpdateDefinition <T> update, UpdateOptions options = null, CancellationToken cancellationToken = default) where T : BaseMongoEntity { return(Database.GetCollection <T>(typeof(T).Name).UpdateOne(filter, update.Set(s => s.UpdateTime, DateTime.Now), options, cancellationToken)); }
/// <summary> /// 查询更新单条(自动更新UpdateTime字段) /// </summary> /// <typeparam name="T">文档类型</typeparam> /// <param name="id">文档默认ID</param> /// <param name="update">更新定义</param> /// <param name="options">更新操作设置</param> /// <param name="cancellationToken">取消操作设置</param> /// <returns></returns> public T FindOneAndUpdateOne <T>( string id, UpdateDefinition <T> update, FindOneAndUpdateOptions <T> options = null, CancellationToken cancellationToken = default) where T : BaseMongoEntity { return(Database.GetCollection <T>(typeof(T).Name).FindOneAndUpdate <T>(u => u.Id == id, update.Set(s => s.UpdateTime, DateTime.Now), options, cancellationToken)); }
/// <summary> /// 查询更新单条(自动更新UpdateTime字段) /// </summary> /// <typeparam name="T">文档类型</typeparam> /// <param name="filter">Lambda过滤器</param> /// <param name="update">更新定义</param> /// <param name="options">更新操作设置</param> /// <param name="cancellationToken">取消操作设置</param> /// <returns></returns> public T FindOneAndUpdateOne <T>( Expression <Func <T, bool> > filter, UpdateDefinition <T> update, FindOneAndUpdateOptions <T> options = null, CancellationToken cancellationToken = default) where T : BaseMongoEntity { return(Database.GetCollection <T>(typeof(T).Name).FindOneAndUpdate(filter, update.Set(s => s.UpdateTime, DateTime.Now), options, cancellationToken)); }