MongoDB Learning Note ~ Update of the official drive nested array object

Source: Internet
Author: User

Back to Catalog

For the array object MongoDB itself is supported, but for the update of the array, MongoDB's CSharp driver currently supports only one level, that is, your object contains an array, and the array includes an array, which represents two levels, which is not supported when updating a subarray, the CSharp driver. What I'm going to say today is how to make it support the update of the Subarray, and here's the data structure I gave

In MongoDB's CSharp driver, the general Update method is as follows

  New " $set " ,                                          New Bsondocument ("orderlist.$.  UserName"," occupy the Order ")                              }}; MongoRepository.Collection.Update (query, Update);

The above code can quickly update the specified level two array orderlist in the Username field, and if you want to update OrderDetail is not so easy, csharp flooding is not currently supported, of course, you will certainly follow the gourd painting, but the result is a failure, Just like the following code (failed, only jiwang new driver)

  New " $set " ,                                          New Bsondocument ("orderlist.$.  Orderdetail.productname"," accounted for ")                              }}; MongoRepository.Collection.Update (query, Update);

As a result, OrderDetail's ProductName has not changed, hehe.

To find the reason, to find the information, fortunately, found a good idea, that is, to update the array within the arrays, you need to locate the superior data, As Orderlist.0.orderdetail, this represents the OrderDetail array object under the OrderList array element (an entity) labeled 0, which of course is not so easily available.

We need to iterate through the array, find the conditions to meet, and then break.

varMongorepository =NewMongodb.data.core.mongoofficialrepository<person>(); varquery = Query.eq ("orderlist._id", twoid); varOO =mongoRepository.Collection.Find (query).            FirstOrDefault (); varUpdate =Newupdatedocument (); BOOLIsexit =false;  for(intj =0; J < Oo. Orderlist.count; J + +)            {                varOD =Oo. ORDERLIST[J].                OrderDetail; Oo. ORDERLIST[J]. UserName="Big Account of change";  for(inti =0; I < OD. Count; i++)                {                    if(Od[i]. Id = =Threeid) {Od[i]. ProductName="big accounted for modified orders"; #regionPull first, push again//update = new UpdateDocument {"$pull",//new Bsondocument ("OrderList.") +j+ ". OrderDetail ",//new Bsondocument ("_id", Threeid))//                                 }}; //mongoRepository.Collection.Update (Query1, Update); //update = new UpdateDocument {"$push",//new Bsondocument ("OrderList.") +j+ ". OrderDetail ",//new Bsondocument (Od[i]. ToDictionary ()))//                            }}; //mongoRepository.Collection.Update (Query1, Update);                        #endregion                        #regionDirect setUpdate=Newupdatedocument {{"$set",                                                                NewBsondocument ("orderlist.$. UserName", Oo. ORDERLIST[J].                        UserName)}};                        MongoRepository.Collection.Update (query, Update); Update=Newupdatedocument {{"$set",                                                          NewBsondocument ("orderlist."+j+". OrderDetail."+I,Newbsondocument (Od[i].                        ToDictionary ()))}};                        MongoRepository.Collection.Update (query, Update); #endregionIsexit=true;  Break; }                }                if(isexit) Break; }

The above code, we see there are two ways to update the collection, $pull and $push method and $set method, we can choose according to preferences, can achieve our goal, ToDictionary is my encapsulation method, meaning to convert the properties of the class object into a dictionary, And do the MongoDB _id primary key processing, the code is as follows

/// <summary>        ///convert an object property to a dictionary/// </summary>        /// <param name= "O" ></param>        /// <returns></returns>         Public StaticDictionary<string, Object> todictionary ( This Objecto) {Dictionary<string, object> map =Newdictionary<string,Object>(); Type T=O.gettype (); propertyinfo[] Pi= T.getproperties (BindingFlags.Public |bindingflags.instance); foreach(PropertyInfo Pinchpi) {MethodInfo mi=P.getgetmethod (); if(Mi! =NULL&&mi. IsPublic) {if(P.name = ="Id") map. ADD ("_id", MI. Invoke (O,New( object[] {})); Elsemap. Add (P.name, MI. Invoke (O,New( object[] {})); }            }            returnmap; }    }

The quest for MongoDB is still going on ...

Back to Catalog

MongoDB Learning Note ~ Update of the official drive nested array object

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.