Developing real estate information collectors with WPF + MongoDB (3) -- getting started with MongoDB

Source: Internet
Author: User
Tags automap mongodb driver mongodb query

It has been a long time before the previous text. On the one hand, my work is a little busy, and I have encountered some problems which have not been solved yet. In this case, I willArticleAt the end of this article, let's go to the topic of this article-MongoDB getting started.

As I am a beginner, I am only writing a very simple entry content ~~~~

  • Database Installation
    Database installation is everywhere on the Internet. I am also from Google, so don't worry. Here is the link. Install and start MongoDB
    In addition, for beginners, I think using command lines is the best way to learn database commands. But after all, it is quite tiring. Two GUI MongoDB database management tools are also recommended here.
    1. mongovue is a tool developed by foreigners.
    2. magicmongodbtool is developed by magicdict In the atom. You can worship it ~ Haha. The author has open-source projects. If you are interested, you can download them.Source codeLook at it by yourself.

  • Database Connection
    Before connecting to the database, we first need to determine the MongoDB driver we want to use. There are actually a lot of drivers, but I have never touched it. It's also a beginner. Let's start with the official driver. After downloading and compiling, there should be two DLL files: MongoDB. bson. dll and MongoDB. Driver. dll.
    Below is my database connection Code :
     ///  <Summary>  
    /// Connect to database
    /// </Summary>
    /// <Param name = "info"> </param>
    Public Static Void Connect (dbinfo info)
    {
    Dbhelper.info = Info;
    If (Info. dbtype = dbtype. MongoDB)
    {
    Mongoserversettings mss = New Mongoserversettings ();
    MSS. connectionmode = connectionmode. Direct; // Database Connection Mode
    // MSS. connectionmode = connectionmode. replicaset; // This is for the database set (multiple database addresses)
    MSS. connecttimeout = New Timespan ( 0 , 0 , 20 ); // Timeout 20 s
    MSS. Server = New Mongoserveraddress (info. Source, info. Port ); // Database
    // MSS. servers is for the database set

    // MSS. defaultcredentials = new inclucredentials (info. uid, info. pwd, true );
    Internal Server MS = New Consumer server (MSS );
    Required databaseset1_mds = New Using databasesettings (MS, info. dbname );

    Ms. Connect ();
    DB = New Relational Database (MS, MDS ); // Save the recovery database information for subsequent calls
    }
    }

    In this way, you can connect to the database.

  • Mapping
    After the database is connected, you need to map the classes and data you have defined. The corresponding ing method (MongoDB. bson. dll) is provided in the driver:
     
    Bsonclassmap. registerclassmap <t> (Cm =>
    {
    Cm. automap ();
    });

    In addition, you can directly set the ID and ID generation method during mapping:

    Bsonclassmap. registerclassmap <t> (Cm =>
    {
    Cm. automap ();
    Cm. setidmember (CM. getmembermap (C => C. ID ));
    Cm. idmembermap. setidgenerator (stringobjectidgenerator. instance );
    });

    If this parameter is not set during ing, you can also add the bsonid attribute for the corresponding Id field when defining the class:

     
    [Bsonid (idgenerator =Typeof(Stringobjectidgenerator)]
    Public Virtual StringId {Get;Set;}

    You can also set the attribute not mapped to the database through the attribute, so that when reading and writing the database, this attribute will be ignored:

     
    [Bsonignore]
    Public StringFavimage {Get;Set;}
  • Add, delete, modify, and query Databases
    Next, we can read and write the database through the driver.
    Before getting data, we need to get the collection mapped to the corresponding class:
     
    Dbhelper. DB. getcollection <t> (name );//Name indicates the collection name mapped to T.

    The name parameter must be specified for the getcollection method. In fact, I think the collection name corresponding to T should have been determined before the ing. Why must the name be specified here? Or are there other methods I don't know?
    The read data of MongoDB is the find command. The find/findall method is also used in the driver.

     
    Getcollection <t> (). findall ();

    In practice, we usually have query conditions and sorting conditions.
    The MongoDB query condition is imongoquery and the sorting condition is imongosortby.

     
    Getcollection <t> (). Find (query). setsortorder (sortby );

    You can also use setskip and setlimit for paging:

     
    Getcollection <t> (). Find (query). setsortorder (sortby). setskip (skip). setlimit (Limit );

    The following describes how to obtain the corresponding data based on tags and sort the data based on the Update time. The paging function is not available yet:

     ///  <Summary> 
    /// Get tag data
    /// </Summary>
    /// <Param name = "ht"> </param>
    /// <Returns> </returns>
    Public Static List {
    Querycomplete query = Null ;
    If (Ht! = Null )
    {
    Query = query. And (
    Query. GTE (housetag. pnamearea, HT. areamin ),
    Query. Lte (housetag. pnamearea, HT. areamax ),
    Query. GTE (housetag. pnameprice, HT. pricemin ),
    Query. Lte (housetag. pnameprice, HT. pricemax ),
    Query. GTE (housetag. pnamepricetotal, HT. pricetotalmin ),
    Query. Lte (housetag. pnamepricetotal, HT. pricetotalmax ),
    Query. GTE (housetag. pnameyear, HT. yearmin ),
    Query. Lte (housetag. pnameyear, HT. yearmax)
    );
    If (! String . Isnullorempty (HT. Zone ))
    {
    MongoDB. bson. bsonregularexpression Reg = New MongoDB. bson. bsonregularexpression ( String . Format ( " * {0 }* " , HT. Zone ));
    Query = query. And (query, query. Matches (housetag. pnamezone, REG ));
    }
    }
    Return Revoke helper. findall " Updatetime " ). Tolist ();
    }

    After obtaining the data, the next step is to save the data. It is easier to save (ADD and modify) The data. You can simply use save. Besides, I have not processed the changed data here, every time the object is saved, the whole object is updated (efficiency is definitely not suitable, but programming is more convenient than a little ):

     ///  <Summary>  
    /// Update a data set
    /// </Summary>
    /// <Typeparam name = "T"> </typeparam>
    /// <Param name = "listentity"> </param>
    Public Static Void Save <t> (ienumerable <imongoentity> listentity)
    Where T: Class , Imongoentity
    {
    If (Listentity! = Null )
    {
    Collect collection <t> Col = getcollection <t> ();
    Foreach (Imongoentity entity In Listentity)
    {
    Col. Save (entity );
    }
    }
    }

    The difference between data deletion and data update is that you need to obtain the data based on the corresponding conditions (imongoquery ):

     ///  <Summary>  
    // Delete a data set
    /// </Summary>
    /// <Typeparam name = "T"> </typeparam>
    /// <Param name = "listentity"> </param>
    Public Static Void Remove <t> (ienumerable <imongoentity> listentity)
    Where T: Class , Imongoentity
    {
    If (Listentity! = Null )
    {
    Collect collection <t> Col = getcollection <t> ();
    Foreach (Imongoentity entity In Listentity)
    {
    Col. Remove (query. eq ( " ID " , Entity. ID ));
    }
    }
    }

At the end of this article, I will explain the problems I encountered earlier at the beginning of this article.

Yes. I think the target users of this real estate information collector are mainly friends who pay attention to the real estate transaction information. These people cannot expect them to be an IT employee, or they hope they can install and deploy MongoDB very smoothly. So I want to see ifProgramWhen running, determine whether the MongoDB service exists and whether the MongoDB database has been started. If there is no service, create a service. If it is not started, start the corresponding service. In short, as long as you open the Real Estate Information Collector, you can directly use it without other services. However, I tried it for a long time and failed to implement the function of creating the MongoDB service.

My idea is to put the corresponding directory of MongoDB together in the root directory of the program at the time of release. Then, when there is no corresponding service, start the corresponding command line to automatically create the MongoDB service and start it.

Therefore, there are two problems:

    1. Automatically create a MongoDB service.
    2. Automatically runs the MongoDB service.

These two problems can also be extended to creating and starting services (including any other services ).

Do you have any suggestions or implementation methods? If so, comments and private messages are welcome. It is better to have ready-made code. Haha.

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.