I also just learned about MongoDB databases, and I have not figured out many problems. Let's talk about updates today. Maybe it's because I'm used to relational databases. The operation idea is always there.
Let's talk about the update command in the database.
1. Update () command
DB. collection. Update (criteria, objnew, upsert, multi)
Criteria: Query condition for update, similar to
Objnew: The update object and some updated operators (such as $, $ Inc...) can also be understood as
Upsert: this parameter indicates whether to insert objnew if no update record exists. True indicates insertion. The default value is false.
Multi: the default value of MongoDB is false. Only the first record found is updated. If this parameter is set to true, all the records identified by the condition are updated.
Example:
DB. test0.update ({"count": {$ GT: 1 },{$ set: {"Test2": "OK"}); only the first record is updated.
DB. test0.update ({"count": {$ GT: 3 },{$ set: {"Test2": "OK" }}, false, true); all updated
DB. test0.update ({"count": {$ GT: 4 }},{ $ set: {"test5": "OK" }}, true, false); only the first entry is added.
DB. test0.update ({"count": {$ GT: 5 }},{ $ set: {"test5": "OK" }}, true, true); all added
2. Driver Operation samus
It may be that the younger brother has not yet learned the samus driver. Let me talk about it first.
I found that the update method of this driver is to update the whole set through the set. That is to say, if I want to update one of the fields, I have to update the entire set,
Public int Delete (string user_id)
{
Using (mymongodb MDB = new mymongodb ())
{
VaR collection = MDB. getcollection <user> ();
VaR Category = collection. findone (x => X. userid = user_id );
Category. is_del = 1;
Collection. Update (category, new document {"userid", user_id }});
}
}
I first query this record through userid, and update the object value.
But what should I do with batch update?
For example, I want to update is_del = 1 if the gender is male;
I am using a stupid method, first querying in the loop update. If you have a better solution, please leave a message for me to learn.
Public int Delete (INT sex)
{
Using (mymongodb MDB = new mymongodb ())
{
VaR collection = MDB. getcollection <user> ();
VaR Category = collection. Find (x => X. Sex = sex). Documents. tolist <user> ();
Foreach (User U in category)
{
U. is_del = 1;
Collection. Update (u, new document {"userid", U. userid }});
}
}
Return 1;
}
The above are two update methods. We hope you can write more.