示例#1
0
        public static DataContracts.UpdateResult UpdateOne <T>(string collectionName, FilterDefinition <T> filter, UpdateDefinition <T> update, UpdateOptions updateOptions = null, string schemaId = "", Notification notification = null)
        {
            var request = new UpdateOne
            {
                CollectionName = collectionName,
                OutputMode     = JsonOutputMode.Strict,
                Filter         = filter.ToJson(),
                Notification   = notification,
                Update         = update.ToJson(),
                UpdateOptions  = updateOptions,
                SchemaId       = schemaId
            };

            var response = Send <UpdateOneResponse>("entities/" + collectionName, request, "PUT");

            return(response.Result);
        }
        /// <summary>
        /// 按ID更新多个属性
        /// </summary>
        /// <param name="objId"></param>
        /// <param name="upProperty"></param>
        /// <returns></returns>
        public bool UpdatePropertyById(ObjectId objId, UpdateDefinition <T> upProperty)
        {
            FilterDefinition <T> filter = Builders <T> .Filter.Eq("_id", objId);

            try
            {
                UpdateResult result = MongoCollection.UpdateOneAsync(filter, upProperty).Result;
                if (result.ModifiedCount == 0 && result.MatchedCount == 1)
                {
                    MongoLog.Logger.Warning($"按ID更新多属性操作取消,更新的属性与原属性相同。Id值为:[{objId.ToString()}]\r\n类型为:[{typeof(T).FullName}]\r\n更新属性信息为:[{upProperty.ToJson()}]\r\n操作结果为:[{result.ToJson()}]");
                    return(true);
                }
                if (1 != result.ModifiedCount)
                {
                    // 更新失败,记录日志
                    MongoLog.Logger.Error($"按ID更新多属性操作取消,无数据被更新。Id值为:[{objId.ToString()}]\r\n类型为:[{typeof(T).FullName}]\r\n更新属性信息为:[{upProperty.ToJson()}]\r\n操作结果为:[{result.ToJson()}]");
                    return(false);
                }
                return(true);
            }
            catch (System.TimeoutException te)
            {
                MongoLog.Logger.Warning(te, "数据库链接超时。链接字符串:" + Provider.Connection.ConnectionString());
                throw;
            }
            catch (Exception ex)
            {
                MongoLog.Logger.Warning(ex, "操作异常终止。");
                throw;
            }
        }