MongoDB basic Tutorial: CURD help class, mongodbcurd
I have been studying MongoDB for the last two days, a powerful document database. My biggest feeling is that compared with traditional relational databases such as SQL or MSQ, it is much simpler to use and configure. Both cluster configuration and Failover save a lot of tedious steps, but what is the most important? It solves the I/O bottleneck of traditional relational databases, greatly improves the work efficiency, and is suitable for querying massive data.
Of course, you may have heard a lot of things, and your ears have been worn out.
There will be a lot of articles on MongoDB in the blog site, but most of them are about installing, copying, failover, etc. For those who have learned how to install but want to use it, they feel that they have no way to start, the blogger feels the same, so I will share it here. NET, how to use MongoDB for basic CURD, and write a basic general help class. If you think you need it, you can use it. If you think it is useful, you can give a thumbs up, really, giving likes makes me happier than giving money !!!
1. Two common operating Media
In. NET, there are two kinds of commonly used operating media for MongoDB: The BsonDocument object model and the custom object type.
(1) BsonDocument
MongoDB is a document-based database. In the Collection of MongoDB, each document can be considered as a Bson (Binary Json) object, so there is a BsonDocument type in the driver, it is a set of key-value pairs of the essential name/value. You can generate a BsonDocument document using the following method, and Add a key-value Pair using the Add method, the BsonDocumen object generated in this way can be directly inserted into the Collection.
BsonDocument student1 = new BsonDocument();student1.Add("sid", 10);student1.Add("name", "Will10");student1.Add("gender", "Male");student1.Add("age", 26);
(2) custom object type
We may use custom object types every day. There is nothing to do with it. If you want to use custom object types to operate data sets in MongoDB, in this case, the field names in your object must be consistent with those in MongoDB (for example, if _ id is different from ID, an error is returned), and The _ id field must be included.
Both of the above methods can be used, and each method has its own advantages. Using a custom type method, you can make the documents in the collection have a unified mode; the BsonDocument method supports more document modes. That is to say, if the document in a collection has various modes, the BsonDocument method is more flexible.
2. Connect to the database
There are more than one MongoDB driver for. NET. The driver is also recommended by the official team. Here, the blogger chooses the officially recommended driver mongocsharpdriver, which can be downloaded and installed through NuGet.
The database connection code is as follows:
public static void GetColloection(string IP, string Port, string Database, string CollectionName){ string connection = string.Format("mongodb://{0}:{1}", Database, Port); MongoClient client = new MongoClient(connection) var server = client.GetServer(); collection = server.GetDatabase(Database).GetCollection(CollectionName);}
Here, the blogger encapsulates a connection method. The connection method is not good and flexible enough. When switching data sets, you need to re-enter the IP address and Port, you can encapsulate the appropriate ones.
3. Query
(1) query all data in the set and return the List set:
public static List<T> GetList<T>(){ return collection.FindAllAs<T>().ToList();}
(2) query the corresponding data in the set by Id and return the data entity: (your VS needs to have the corresponding Object model)
public static T GetById<T>(int Id){ var query = Query.EQ("_id", Id); return collection.FindOneAs<T>(query);}
The Query Builder method is used here, which is a more concise Query method than QueryDocument (not used here). EQ means "=", and GT (>). When querying in this way, we need to use the builder in the driver to generate the query. Therefore, the following using statement must be referenced:
using MongoDB.Driver.Builders;
The following statement can be used to query students older than 20:
var query = Query.GT("age", 20); foreach (var student in collection.Find(query)) { Console.WriteLine(student); }
(3) query the corresponding data entity based on the field
In many cases, we will query data by Id, but in some cases we may use other data for query. Here we encapsulate a method:
public static List<T> GetValueByKey<T>(string key, string value){ var query = Query.EQ(key, value); return collection.FindAs<T>(query).ToList();}
(4) Linq Query
After the driver's 1.8 release, the official driver can support the LINQ operation. We only need to use the following using statement to support the query in the LINQ mode.
using MongoDB.Driver.Linq;
Therefore, you can query students older than 20, or use the following method:
var linquery = from e in collection.AsQueryable<Student>() where e.age > 20 select e;var linquery1 = collection.AsQueryable<Student>().Where(e => e.age > 20);
4. Added
(1) The Insert method is commonly used. It has five overload values and can be selected based on the actual situation. Here we use its generic method Insert <T> (T document ):
public static void Insert<T>(T model){ try { collection.Insert(model); } catch (Exception ex) { throw new Exception(ex.Message); }}
(2) Add an object set
public static void Insert<T>(List<T> list){ try { foreach (var model in list) { collection.Insert(model); } } catch (Exception ex) { throw new Exception(ex.Message); }}
5. Modify
There are two ways to modify: Save and Update. Method encapsulation is not performed here. An example is provided.
(1) Save
Static void Save (empty collection) {var query = Query. EQ ("_ id", 9); var model = collection. FindOneAs <goods> (query); if (model! = Null) {model. title = "Modify test"; collection. Save (model );}}
(2) Update
Static void Update (distinct collection) {var query = Query. EQ ("_ id", 8); var update = Update <goods>. set (x => x. title, "Update modification test"); collection. update (query, update );}
6. Delete
Deletion is relatively simple. Examples and encapsulation methods are provided:
(1) Example
static void Remove(MongoCollection collection){ var query = Query.EQ("_id", 11); collection.Remove(query);}
(2) Encapsulation Method
public static void Remove(IMongoQuery query){ try { collection.Remove(query); } catch (Exception ex) { throw new Exception(ex.Message); }}
Well, basically, CURD is done here. I hope the things mentioned above can help you. To be honest, MongoDB is really powerful, but what about it, at the beginning, there will certainly be a very aggressive process. The bloggers are still in a very aggressive process, while sharing and helping them sort out their work. In the next article, MongoDB will write a copy set and parts, but won't write any operations. After all, there is a search engine in the Garden (mainly because the bloggers did not learn it themselves ), I will write down the error points in the use process and their principles. For example, how to re-select a new Master and the type and role of Slave after the Mater is down.