MongoDB更新操作
/// 构建Mongo的更新表达式 /// </summary> /// <param name="entity"></param> /// <returns></returns> private List<UpdateDefinition<StudentModels>> GeneratorMongoUpdate(StudentModels item) { var fieldList = new List<UpdateDefinition<StudentModels>>(); foreach (var property in typeof(StudentModels).GetProperties(BindingFlags.Instance | BindingFlags.Public)) { GenerateRecursion(fieldList, property, property.GetValue(item), item, string.Empty); } return fieldList; } private void GenerateRecursion(List<UpdateDefinition<StudentModels>> fieldList, PropertyInfo property, object propertyValue, StudentModels item, string father) { //复杂类型 if (property.PropertyType.IsClass && property.PropertyType != typeof (string) && propertyValue != null) { //集合 if (typeof (IList).IsAssignableFrom(propertyValue.GetType())) { foreach (var sub in property.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public) ) { if (sub.PropertyType.IsClass && sub.PropertyType != typeof (string)) { var arr = propertyValue as IList; if (arr != null && arr.Count > 0) { for (int index = 0; index < arr.Count; index++) { foreach ( var subInner in sub.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (string.IsNullOrWhiteSpace(father)) GenerateRecursion(fieldList, subInner, subInner.GetValue(arr[index]), item, property.Name + "." + index); else GenerateRecursion(fieldList, subInner, subInner.GetValue(arr[index]), item, father + "." + property.Name + "." + index); } } } } } } //实体 else { foreach (var sub in property.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public) ) { if (string.IsNullOrWhiteSpace(father)) GenerateRecursion(fieldList, sub, sub.GetValue(propertyValue), item, property.Name); else GenerateRecursion(fieldList, sub, sub.GetValue(propertyValue), item, father + "." + property.Name); } } } //简单类型 else { if (property.Name != "_id") //更新集中不能有实体键_id { if (string.IsNullOrWhiteSpace(father)) fieldList.Add(Builders<StudentModels>.Update.Set(property.Name, propertyValue)); else fieldList.Add(Builders<StudentModels>.Update.Set(father + "." + property.Name, propertyValue)); } } } private void button9_Click(object sender, EventArgs e) { string connection = "mongodb://192.168.5.151:27017"; var client = new MongoClient(connection); var database = client.GetDatabase("School"); var collection = database.GetCollection<StudentModels>("Student"); StudentModels model = new StudentModels() { _id = new ObjectId("56c17ead2c7a7527c057f6f5"), AutoId = 29, Name = "fjzhang", Number = "number-update" }; var list = GeneratorMongoUpdate(model); collection.UpdateOneAsync(x => x._id == model._id, Builders<StudentModels>.Update.Combine(list)); }