MongoDB Development Learning

Source: Internet
Author: User
Tags findone mongodb server mongodb version
If you have never been familiar with MongoDB or have a little understanding of MongoDB, if you are a C # developer, take a few minutes to read this article. This article will take you step by step to get started easily. Read directory 1: Introduction 2: feature 3: Download, install, and enable servers 4: Use cmd.exe to perform database addition, deletion, modification, and query operations 5: More Command 6: cmdd

If you have never been familiar with MongoDB or have a little understanding of MongoDB, if you are a C # developer, take a few minutes to read this article. This article will take you step by step to get started easily. Read directory 1: Introduction 2: feature 3: Download, install, and enable servers 4: Use cmd.exe to perform database addition, deletion, modification, and query operations 5: More Command 6: cmdd

If you have never been familiar with MongoDB or have a little understanding of MongoDB, if you are a C # developer, take a few minutes to read this article. This article will take you step by step to get started easily.

Reading directory

I. Introduction

Ii. Features

3. Download, install, and enable the server

4. Use cmd.exe to add, delete, modify, and query Databases

V. More commands

Vi. MongoDB syntax comparison with existing Relational Database SQL syntax

7. Visualized client management tool MongoVUE

8. Use the official driver to operate MongoDB in C #

9. Use the samus driver to operate MongoDB in C #

10: Write a batch to enable the Mongodb server.

I. Introduction

MongoDB is a distributed file storage-based database. Written in C ++. It is designed to provide scalable, high-performance data storage solutions for WEB applications.

MongoDB is a high-performance, open-source, and non-pattern document-based database. It is a popular NoSql database.

MongoDB is a product between relational databases and non-relational databases. It has the most abundant functions and features like relational databases. The supported data structure is very loose and is similar to the json bjson format. Therefore, it can store complicated data types. The biggest feature of Mongo is that it supports a very powerful query language. Its syntax is somewhat similar to an Object-Oriented Query Language. It can almost implement most of the functions of querying a single table similar to a relational database ,, it also supports data indexing.

Traditional relational databases are generally composed of three levels: database, table, and record. MongoDB is composed of databases and collections) and document objects. MongoDB has no concept of columns, rows, and links for tables in relational databases, which reflects the free mode.

Ii. Features

It features high performance, ease of deployment, and ease of use, making it easy to store data. Features:

1) oriented to centralized storage, it is easy to store object-type data.

2) Free mode.

3) supports dynamic query.

4) supports full indexing, including internal objects.

5) query is supported.

6) supports replication and fault recovery.

7) use efficient binary data storage, including large objects (such as videos ).

8) automatically process fragments to support scalability at the cloud computing level.

9) supports RUBY, PYTHON, JAVA, C ++, PHP, C #, and other languages.

10) the file storage format is BSON (a json extension ).

11) accessible through the network.

3. Download, install, and enable the server

3.1) The current MongoDB version is 2.0.4 ,:. Provides versions of various platforms. I chose Windows.

3.2) Create the directory E: \ mongodb and decompress the downloaded package to this directory. The binfile contains a pile of. EXE files.

There are two most important files: mongod.exeand cmd.exe.

Mongod.exe is used to connect to the mongo database server, that is, the server side.

Cmd.exe is used to start the MongoDB shell, that is, the client.

Other files:

Mongodump logical backup tool.

Mongorestore logical recovery tool.

Export export data export tool.

Mongoimport data import tool.

3.3) Enable the server

Step 1: create a directory to store MongoDB database files, that is, dbpath. You can create it wherever you like. Here I create E: \ MongoDBFiles. This is for the next step.

Step 2: Open the CMD window and enter the following command:

> E:

& Gt; cd e: \ mongodb \ mongodb-win32-i386-2.0.4 \ bin

> Mongod.exe-dbpath "E: \ mongodbfiles"

The value of the-dbpath parameter in the last command line is the folder created in step 1. This folder must be created before the service is enabled. Otherwise, an error will be reported and mongodb will not be created by itself.

If the operation is successful, the following interface is displayed:

This interface shows some information: for example, the process ID is 2988 and the port number is 27017.

Open the browser and enter: 27017/

We see the following prompt:

"You are trying to access MongoDB on the native driver port. For http diagnostic access, add 1000 to the port number"

By now, the MongoDB Database Service has been successfully started.

4. Use cmd.exe to add, delete, modify, and query Databases

Mongodb is our local client management tool named "cmd.exe ".

4.1) Create a database:

Double-click cmd.exe to display the following interface:

This interface means that the currently connected database is test, which will be created by default by the system. Why is it "to be created? Because the database does not exist at this time, or it is still in the memory and is not created on a physical disk. Believe it or not, you can see that there is nothing except mongod. lock In the MongoDBFiles folder. The database is created only when you execute the data insertion command.

Okay. We don't care about this test for the time being. Create a database named cnblogs.

In the shell command window, type the following command:

> Use cnblogs // use command to switch to the current database. If the database does not exist, a new one is created first.

4.2) create a collection and insert data

In traditional relational databases, tables are created after the database is created, but there is no "table" concept in mongoDB. A corresponding concept is set, that is, collection.

In the shell command window, type the following command:

> Db. users. insert ({'name': 'xumingxiang ', 'sex': 'man '})

// This command inserts a piece of data into the users set. If the set users does not exist, a new one will be created first, and then data will be inserted. The parameter is passed in JSON format.

We need to test data deletion later, so we need to insert another data entry:

> Db. users. insert ({'name': xiangshu ', 'sex': 'man '})

4.3) in the above 4.1) and 4.2) Have we created a database, created a set, and inserted two pieces of data? Have these operations been successfully performed? Let's query:

In the shell command window, type the following command:

> Show dbs // display all databases

> Show collections // display all collections in the current database

> Db. users. find () // display all data documents in the users set

The shell interface is as follows:

See what I marked in red. This indicates that the previous operation was successful. We also see that the system assigns a unique primary key _ id to each record.

4.4) update data

Now we need to change the sex of the second data to female, that is, "women"

In the shell command window, type the following command:

> Db. users. update ({'name': 'xiangshu'}, {'$ set': {'sex': 'women'}, upsert = true, multi = false)

Several parameters are explained as follows:

1. query Conditions

2. Updated Fields

Third: insert if no data exists

Fourth: whether to allow modification of multiple records

4.5) delete records

Now we want to set the first record, that is, 'name' to 'xumingxiang '.

In the shell command window, type the following command:

> Db. users. remove ({'name': 'xumingxiang '})

Check whether the operation is successful in step 4) 5. In the shell command window, type the following command:

> Db. users. find ()

From the output page, we can see that there is only one 'name' with 'xiangshu', and its 'sex 'is 'women', which 4) 5) the two steps are successful.

4.6) delete all records

> Db. users. remove ()

4.7) delete collection

> Db. users. drop () // If the deletion is successful, "true" is returned; otherwise, "false" is returned"

4.8) Delete the current database

> Db. dropDatabase ()

5. More commands

Db. AddUser (username, password) Add User

Db. auth (usrename, password) sets database connection Verification

Db. cloneDataBase (fromhost) clone a database from the target server

Db. commandHelp (name) returns the help for the command

Db. copyDatabase (fromdb, todb, fromhost) copy the database fromdb --- source database name, todb --- target database name, fromhost --- source database server address

Db. createCollection (name, {size: 3333, capped: 333, max: 88888}) to create a dataset, equivalent to a table

Db. currentOp () cancels the current operation of the current database

Db. dropDataBase () Delete the current database

Db. eval (func, args) run code server-side

Db. getCollection (cname) gets a data set. In the same usage: db ['cname'] or

Db. getCollenctionNames () Get the name list of all data sets

Db. getLastError () returns the message indicating the last error.

Db. getLastErrorObj () returns the last error object

Db. getMongo () gets the connection object of the current server get the server

Db. getMondo (). setSlaveOk () allow this connection to read from then nonmaster membr of a replica pair

Db. getName () returns the name of the database to be operated on.

Db. getPrevError () returns the previous error object

Db. getProfilingLevel ()

Db. getReplicationInfo () to obtain duplicate data

Db. getSisterDB (name) get the db at the same server as this onew

Db. killOp () Stop (kill) the current operation in the current database

Db. printCollectionStats () returns the dataset status of the current database

Db. printReplicationInfo ()

Db. printSlaveReplicationInfo ()

Db. printShardingStatus () returns whether the current database is a shared database

Db. removeUser (username) delete a user

Db. repairDatabase () repairs the current database

Db. resetError ()

Db. runCommand (cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj: 1}

Db. setProfilingLevel (level) 0 = off, 1 = slow, 2 = all

Db. shutdownServer () Close the current service program

Db. version () returns the version information of the current program.

Db. test. find ({id: 10}) returns the test dataset ID = 10

Db. test. find ({id: 10}). count () returns the total number of data in the test dataset ID = 10.

Db. test. find ({id: 10}). limit (2) returns the dataset whose test dataset ID = 10 starts from the second one.

Db. test. find ({id: 10}). skip (8) returns the data set from 0 to the eighth in the test dataset ID = 10.

Db. test. find ({id: 10}). limit (2). skip (8) returns the data from the second to the eighth in the test dataset ID = 1 =.

Db. test. find ({id: 10}). sort () returns the sorting dataset of the test dataset ID = 10.

Db. test. findOne ([query]) returns a data record that meets the condition.

Db. test. getDB () returns the name of the database to which the dataset belongs.

Db. test. getIndexes () returns index information for some datasets.

Db. test. group ({key:..., initial:..., reduce:... [, cond:...]})

Db. test. mapReduce (mayFunction, performancefunction, )

Db. test. remove (query) deletes a piece of data in the dataset.

Db. test. renameCollection (newName) rename some dataset names

Db. test. save (obj) inserts a data entry into the dataset.

Db. test. stats () returns the status of this dataset.

Db. test. storageSize () returns the storage size of this dataset.

Db. test. totalIndexSize () returns the size of the index file for this dataset.

Db. test. totalSize () returns the total size of some datasets.

Db. test. update (query, object [, upsert_bool]) updates a piece of data in this dataset.

Db. test. validate () verify this dataset

Db. test. getShardVersion () returns the shared version of the dataset.

Vi. Comparison between MongoDB syntax and SQL Syntax of existing relational databases

MongoDB syntax MySql syntax

Db. test. find ({'name': 'foobar'}) <=> select * from test where

Db. test. find () <=> select * from test

Db. test. find ({'id': 10}). count () <=> select count (*) from test where ID = 10

Db. test. find (). skip (10). limit (20) <=> select * from test limit 10, 20

Db. test. find ({'id': {$ in: [25, 35, 45] }}) <=> select * from test where ID in (25, 35, 45)

Db. test. find (). sort ({'id':-1}) <=> select * from test order by ID desc

Db. test. distinct ('name', {'id': {$ lt: 20 }}) <==> select distinct (name) from test where ID <20

Db. test. group ({key: {'name': true}, cond: {'name': 'foo'}, reduce: function (obj, prev) {prev. msum + = obj. marks ;}, initial: {msum: 0 }}) <=> select name, sum (marks) from test group by name

Db. test. find ('this. ID <20', {name: 1}) <=> select name from test where ID <20

Db. test. insert ({'name': 'foobar', 'age': 25}) <=> insert into test ('name', 'age') values ('foobar ', 25)

Db. test. remove ({}) <=> delete * from test

Db. test. remove ({'age': 20}) <=> delete test where age = 20

Db. test. remove ({'age': {$ lt: 20 }}) <=> elete test where age <20

Db. test. remove ({'age': {$ lte: 20 }}) <==> delete test where age <= 20

Db. test. remove ({'age': {$ gt: 20 }}) <=> delete test where age> 20

Db. test. remove ({'age': {$ gte: 20 }}) <=> delete test where age> = 20

Db. test. remove ({'age': {$ ne: 20 }}) <=> delete test where age! = 20

Db. test. update ({'name': 'foobar'}, {$ set: {'age': 36 }}) <==> update test set age = 36 where

Db. test. update ({'name': 'foobar'}, {$ inc: {'age': 3 }}) <==> update test set age = age + 3 where

Note that the preceding commands are case sensitive.

7. Visualized client management tool MongoVUE

Although it is feasible to use cmd.exe to manage databases and its functions are quite powerful, it is tedious and inefficient to use commands every time. The following describes the virtual Vue, a visual operation management tool for Windows.

:

The running effect is as follows:

8. Use the official driver to operate MongoDB in C #

8.1) download and install

To use MongoDB in C #, you must first have a C # drive supported by MongoDB. C # has many types of drivers, such as samus. Most of the Implementation ideas are similar. Here we first use the official mongo-csharp-driver. The current version is 1.4.1.

:

After compilation, two dll files are obtained.

MongoDB. Driver. dll: as the name suggests, the Driver

MongoDB. Bson. dll: serialization, Json-related

Then reference the two dll files in our program.

The following section briefly demonstrates how to use C # to add, delete, modify, and query MongoDB.

8.2) connect to the database:

Before connecting to the database, make sure that your MongoDB has been enabled.

// Database connection string

Const string strconn = "mongodb: // FIG: 27017 ";

// Database Name

Const string dbName = "cnblogs ";

// Create a database link

Login server = MongoDB. Driver. Login server. Create (strconn );

// Obtain the database cnblogs

Relational Database db = server. GetDatabase (dbName );

8.3) insert data:

Now that the data is opened, we have to add the data. We need to add a User "record" to the Users set.

There is no table concept in MongoDB, so you do not need to create a table before inserting data.

But we have to define the Users model of the data to be inserted.

Users. cs:

Public class Users

{

Public ObjectId _ id; // BsonType. ObjectId corresponds to MongoDB. Bson. ObjectId

Public string Name {get; set ;}

Public string Sex {set; get ;}

}

The _ id attribute must be available. Otherwise, an error occurs when updating data: "Element '_ id' does not match any field or property of class ".

Okay. Now let's see how to write the code for adding data:

Public void Insert ()

{

// Create a database link

Login server = MongoDB. Driver. Login server. Create (strconn );

// Obtain the database cnblogs

Relational Database db = server. GetDatabase (dbName );

Users users = new Users ();

Users. Name = "xumingxiang ";

Users. Sex = "man ";

// Obtain the Users set. If the database does not exist, create a new one first.

Collect collection col = db. GetCollection ("Users ");

// Execute the insert operation

Col. Insert (Users );

}

8.4) update data

Public void Update ()

{

// Create a database link

Login server = MongoDB. Driver. Login server. Create (strconn );

// Obtain the database cnblogs

Relational Database db = server. GetDatabase (dbName );

// Obtain the Users set

Collect collection col = db. GetCollection ("Users ");

// Define the query condition for obtaining the "Name" value as "xumingxiang"

Var query = new QueryDocument {"Name", "xumingxiang "}};

// Define the update document

Var update = new UpdateDocument {"$ set", new QueryDocument {"Sex", "wowen "}}}};

// Perform the update operation

Col. Update (query, update );

}

8.5) delete data

Public void Delete ()

{

// Create a database link

Login server = MongoDB. Driver. Login server. Create (strconn );

// Obtain the database cnblogs

Relational Database db = server. GetDatabase (dbName );

// Obtain the Users set

Collect collection col = db. GetCollection ("Users ");

// Define the query condition for obtaining the "Name" value as "xumingxiang"

Var query = new QueryDocument {"Name", "xumingxiang "}};

// Perform the delete operation

Col. Remove (query );

}

8.6) query data

Public void Query ()

{

// Create a database link

Login server = MongoDB. Driver. Login server. Create (strconn );

// Obtain the database cnblogs

Relational Database db = server. GetDatabase (dbName );

// Obtain the Users set

Collect collection col = db. GetCollection ("Users ");

// Define the query condition for obtaining the "Name" value as "xumingxiang"

Var query = new QueryDocument {"Name", "xumingxiang "}};

// Query data in all sets

Var result1 = col. FindAllAs ();

// Query the first data of a specified query condition. The query condition can be set by default.

Var result2 = col. FindOneAs ();

// Query all data of the specified query Condition

Var result3 = col. FindAs (Query );

}

9. Use the samus driver to operate MongoDB in C #

Next, we will introduce a third-party drive samus, which is a much used driver with fast update frequency. The samus driver supports both normal operations and Linq and Lambda expressions.

: Https://github.com/samus/mongodb-csharp

Download and compile two dll files.

Main Program of MongoDB. dll driver

MongoDB. GridFS. dll is used to store large files.

Here we can reference MongoDB. dll. This document does not use MongoDB. GridFS. dll. We will not introduce it for the time being. Ignore it.

The database connection and CRUD operations are as follows:

// Database connection string

Const string strconn = "mongodb: // FIG: 27017 ";

// Database Name

Const string dbName = "cnblogs ";

// Define the database

Relational Database db;

///

/// Open the database link

///

Public void GetConnection ()

{

// Define the Mongo Service

Mongo mongo = new Mongo (strconn );

// Open the connection

Mongo. Connect ();

// Obtain the cnblogs of the database. It is automatically created if it does not exist.

Db = mongo. GetDatabase (dbName) as your database;

}

///

/// Add data

///

Public void Insert ()

{

Var col = db. GetCollection ();

// Or

// Var col = db. GetCollection ("Users ");

Users users = new Users ();

Users. Name = "xumingxiang ";

Users. Sex = "man ";

Col. Insert (users );

}

///

/// Update data

///

Public void Update ()

{

Var col = db. GetCollection ();

// Find the first record whose Name is xumingxiang

Users users = col. FindOne (x => x. Name = "xumingxiang ");

// Or

// Users users = col. FindOne (new Document {"Name", "xumingxiang "}});

Users. Sex = "women ";

Col. Update (users, x => x. Sex = "man ");

}

///

/// Delete data

///

Public void Delete ()

{

Var col = db. GetCollection ();

Col. Remove (x => x. Sex = "man ");

/// Or

//// Find the first record with the Name value of xumingxiang

// Users users = col. FindOne (x => x. Sex = "man ");

// Col. Remove (users );

}

///

/// Query data

///

Public void Query ()

{

Var col = db. GetCollection ();

Var query = new Document {"Name", "xumingxiang "}};

// Query all data of the specified query Condition

Var result1 = col. Find (query );

// Query the first data of a specified query Condition

Var result2 = col. FindOne (query );

// Query data in all sets

Var result3 = col. FindAll ();

}

More APIs are for your own experience.

10. Write a batch to enable the Mongodb server.

Every time you open the Mongodb server, you have to open the CMD window, and repeat the command to repeat it. Are you also bored? I hate doscommand.

How can I enable the Mongodb server by clicking the mouse? You may have thought that writing a batch processing program won't be done. Yes, that's it. This batch processing is very simple.

The Code is as follows:

@ Echo

@ Pause

Mongod-repair-dbpath "E: \ mongodbfiles"

Mongod-dbpath "E: \ mongodbfiles"

@ Pause

Note: "mongod-repair-dbpath" E: \ mongodbfiles "is used to solve the problem of" Unclean shutdown detected mongodb "error at startup ".

Save the stored Beibei to the local directory as A. batfile, and then put it in the same directory as mongod.exe. Double-click it to OK.

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.