Recordof Mongodb database update update operation of an array or an object

  It has always been updated for a number of simple basic types, until one day write the update operation covering a certain field (this field array). A problem, the database appeared _t, _v ...... a little ignorant. Of course, a prerequisite if we update the time setting type will not have this problem, this problem is that we will array assignment to a variable of type object; because of the time asked about co-workers, she gives the solution: mongodb drive to deserialize it. So the problem is solved, and today have time to record it and found objects update when writing sample code does not work.

  Look at our data, as well as shots after update:

/* 1 */
{
    "_id" : "1",
    "Name" : "ddz001",
    "Age" : 10,
    "Valid" : true,
    "CreateDate" : ISODate("2020-03-28T05:59:43.841Z"),
    "LastUpdatedTime" : ISODate("2020-03-28T05:59:43.841Z"),
    "Details" : {
        "Height" : 169.5,
        "Weight" : 70.5,
        "Married" : true
    },
    "Bookmarks" : [ 
        {
            "Title" : "百度一下",
            "Url" : "https://www.baidu.com/"
        }, 
        {
            "Title" : "必应",
            "Url" : "https://cn.bing.com/"
        }
    ]
}

/* 2 */
{
    "_id" : "2",
    "Name" : "ddz002",
    "Age" : 20,
    "Valid" : true,
    "CreateDate" : ISODate("2020-03-28T05:59:43.841Z"),
    "LastUpdatedTime" : ISODate("2020-03-28T05:59:43.841Z"),
    "Details" : {
        "Height" : 170.5,
        "Weight" : 71.5,
        "Married" : true
    },
    "Bookmarks" : [ 
        {
            "Title" : "搜狗搜索",
            "Url" : "https://www.baidu.com/"
        }, 
        {
            "Title" : "多吉搜索",
            "Url" : "https://www.dogedoge.com/"
        }
    ]
}
Sample Data

  Why is there a problem in the figure above, the print a bit shell commands UpdateDefinition generated, you will find is that,

  Directly behind the method colleague tried it, and then view the resulting statement no problem

  Since UpdateDefinition can be converted into a string, and he also can be assigned directly to a string, for example: UpdateDefinition <BsonDocument> updateDefinition = "";, so I thought for a moment that we direct fight this string should be no problem, of course, this I did not test ah!

  There is also a problem encountered is how to determine the true object of a type, where only needs to know that he is not an object or array (here refers to all). May really have a la carte, I do not know if the judge. Looked at the official document: Type class , but could not find, finally using stupid approach: first serialized to object to a string in the reverse sequence after, he will tell you type. The last problem is that this solution to the problem is not optimal, feeling a bit big waste ...... God knows if there any efficient way, please let us know, thanks again.

  Finally, look at my sample code:

using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;

namespace DDZ.MongodbUpdateArrayTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // clear the table (to empty before new), batch add (initialize some data), query
             // DeleteManyBatchAddFind ();

            // update the data and test Object
             // UpdateArrayOrObject ();

            #region find solutions 
            OtherInfoModel otherInfo = null ;
            List<BookmarkModel> bookmarks = null;
            List<KeyValueModel> keyValueModels = new List<KeyValueModel>()
            {
                new KeyValueModel(){ Key="Name",Value ="ddz001+++" },
                new KeyValueModel(){ Key="Age",Value = 11 },
                new KeyValueModel(){ Key="Valid",Value = false },
                new KeyValueModel(){ Key="LastUpdatedTime",Value=DateTime.Now },
                new KeyValueModel(){ Key="Details",Value = new OtherInfoModel(){ Height=179.5f,Weight=80.5f,Married=false } },
                new KeyValueModel(){ Key="DetailsNull",Value = otherInfo },
                new KeyValueModel()
                {
                    Key="Bookmarks",Value = new List<BookmarkModel>()
                    {
                        new BookmarkModel() { Title="Yandex",Url="https://yandex.com/" },
                        new BookmarkModel() { Title="秘迹搜索",Url="https://mijisou.com/" }
                    }
                },
                 new KeyValueModel(){ Key="BookmarksNull",Value = bookmarks },
            };

            if (keyValueModels.Any())
            {
                var updateDefinitions = new List<UpdateDefinition<BsonDocument>>();
                foreach (var item in keyValueModels)
                {
                    if (item.Value == null)
                    {
                        updateDefinitions.Add(Builders<BsonDocument>.Update.Set(item.Key, BsonNull.Value));
                        continue;
                    }
                    string tempValueForStr = JsonSerializer.Serialize(item.Value);
                    var tempValueForObj = JsonSerializer.Deserialize<object>(tempValueForStr);
                    var tempValueType = ((JsonElement)tempValueForObj).ValueKind;
                    switch (tempValueType)
                    {
                        case JsonValueKind.Object: 
                        case JsonValueKind.Array: {
                                updateDefinitions.Add(Builders<BsonDocument>.Update.Set(item.Key, BsonSerializer.Deserialize<object>(tempValueForStr)));
                                break;
                            }
                        default: {
                                updateDefinitions.Add(Builders<BsonDocument>.Update.Set(item.Key, item.Value));
                                break; 
                            }
                    }
                }
                var updateDefinition = Builders<BsonDocument>.Update.Combine(updateDefinitions);
                string tempUpdateStr = GetJsonStingByUpdateDefinition(updateDefinition);
            }
            #endregion

            Console.WriteLine("Hello World!");
        }

        ///  <the Summary> 
        /// clear the table (to empty before new), batch add (initialize some data), query operation
         ///  </ the Summary> 
        static  void DeleteManyBatchAddFind ()
        {
            var _client = new MongoClient("mongodb://localhost:27017");
            var _database = _client.GetDatabase("FormBuilder");
            var _collection = _database.GetCollection<UpdateArrayTestModel>("UpdateArrayTest");
            //  如果表不存在不报错
            var delCount = _collection.DeleteMany(Builders<UpdateArrayTestModel>.Filter.Empty).DeletedCount;
            var dtNow = DateTime.Now;
            List<UpdateArrayTestModel> initUpdateArrayTestModels = new List<UpdateArrayTestModel>()
            {
                new UpdateArrayTestModel()
                {
                    Id="1",Name="ddz001",Age=10,Valid=true,CreateDate=dtNow,LastUpdatedTime=dtNow,
                    Details=new OtherInfoModel(){ Height=169.5f, Weight=70.5f, Married=true },
                    Bookmarks=new List<BookmarkModel>()
                    {
                        new BookmarkModel(){ Title="百度一下",Url="https://www.baidu.com/" },
                        new BookmarkModel(){ Title="必应",Url="https://cn.bing.com/" }
                    }
                },
                new UpdateArrayTestModel()
                {
                    Id="2",Name="ddz002",Age=20,Valid=true,CreateDate=dtNow,LastUpdatedTime=dtNow,
                    Details=new OtherInfoModel(){ Height=170.5f, Weight=71.5f, Married=true },
                    Bookmarks=new List<BookmarkModel>()
                    {
                        new new BookmarkModel () {the Title = " Sogou search " , the Url = " https://www.baidu.com/ " },
                         new new BookmarkModel () {the Title = " sorafenib search " , the Url = " HTTPS: //www.dogedoge .com / " }
                    }
                }
            };
            _collection.InsertMany(initUpdateArrayTestModels);
            var queryResult = _collection.Find(Builders<UpdateArrayTestModel>.Filter.Empty).ToList();
            var queryResultStr = JsonSerializer.Serialize(queryResult);
        }

        ///  <Summary> 
        /// Update Data Object and test
         ///  </ Summary> 
        static  void UpdateArrayOrObject ()
        {
            //   here also encountered the same problem
             //       1, https://jira.mongodb.org/browse/CSHARP-1984 
            //   other
             //       1, https://www.codeproject.com/Tips/1268019/ How---Csharp MongoDB-to-the Deserialize the JSON-A-Containin 
            //       2, https://blog.csdn.net/mzl87/article/details/85488319 
            var _client = new new MongoClient ( " MongoDB: // localhost: 27017 " );
             var _database = _client.GetDatabase ( " FormBuilder " );
             var _Collection = _database.GetCollection <BsonDocument> ( "UpdateArrayTest");
            List<KeyValueModel> keyValueModels = new List<KeyValueModel>()
            {
                new KeyValueModel(){ Key="Name",Value ="ddz001+++" },
                new KeyValueModel(){ Key="Age",Value = 11 },
                new KeyValueModel(){ Key="Valid",Value = false },
                new KeyValueModel(){ Key="LastUpdatedTime",Value=DateTime.Now },
                new KeyValueModel(){ Key="Details",Value= new OtherInfoModel(){ Height=179.5f,Weight=80.5f,Married=false } },
                new KeyValueModel()
                {
                    Key="Bookmarks",Value = new List<BookmarkModel>()
                    {
                        new BookmarkModel() { Title="Yandex",Url="https://yandex.com/" },
                        new BookmarkModel() { Title="秘迹搜索",Url="https://mijisou.com/" }
                    }
                }
            };
            if (keyValueModels.Any())
            {
                var updateDefinitions = new List<UpdateDefinition<BsonDocument>>();
                foreach (var item in keyValueModels)
                {
                    updateDefinitions.Add(Builders<BsonDocument>.Update.Set(item.Key, item.Value));
                }
                var updateDefinition = Builders<BsonDocument>.Update.Combine(updateDefinitions);
                string tempUpdateStr = GetJsonStingByUpdateDefinition(updateDefinition);
                //var modifiedCount = _collection.UpdateMany(Builders<BsonDocument>.Filter.Eq("_id", "1"), updateDefinition).ModifiedCount;
            }
        }

        /// <summary>
        /// 将UpdateDefinition转为shell字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="updateDefinition"></param>
        /// <returns></returns>
        static string GetJsonStingByUpdateDefinition<T>(UpdateDefinition<T> updateDefinition)
        {
            //  参考网址:
            //  https://qa.1r1g.com/sf/ask/2243338471/
            if (updateDefinition == null) return null;
            //updateDefinition.Render(_collection.DocumentSerializer,_collection.Settings.SerializerRegistry).ToString()
            return updateDefinition.Render(BsonSerializer.SerializerRegistry.GetSerializer<T>(), BsonSerializer.SerializerRegistry).ToString();
        }
    }

    public class UpdateArrayTestModel
    {
        private string _id { get; set; }

        /// <summary>
        /// 主键ID
        /// </summary>
        public string Id { set => this._id = value; get => _id; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }

        ///  <Summary> 
        /// valid
         ///  </ Summary> 
        public  BOOL ! Valid { GET ; SET ;} = to true ;

        /// <summary>
        /// 创建时间
        /// </summary>
        [BsonDateTimeOptions(Kind = DateTimeKind.Unspecified)]
        public DateTime CreateDate { get; set; }

        ///  <Summary> 
        /// last updated
         ///  </ Summary> 
        [BsonDateTimeOptions (the Kind = DateTimeKind.Unspecified)]
         public the DateTime LastUpdatedTime { GET ; SET ;}

        ///  <Summary> 
        /// Other details
         ///  </ Summary> 
        public OtherInfoModel the Details { GET ; SET ;}

        ///  <Summary> 
        /// I Bookmarks
         ///  </ Summary> 
        public the IEnumerable <BookmarkModel> {the Bookmarks GET ; SET ;}
    }

    public class OtherInfoModel
    {
        public float Height { get; set; }
        public float Weight { get; set; }
        public bool Married { get; set; } = true;
    }

    public class BookmarkModel
    {
        public string Title { get; set; }
        public string Url { get; set; }
    }

    public class KeyValueModel
    {
        public string Key { get; set; }
        public object Value { get; set; }
    }
}
Sample Code

 

Guess you like

Origin www.cnblogs.com/du-blog/p/12588077.html