In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about the nature of MongoDB and how to install and configure. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.
If you have never been exposed to MongoDB or know a little bit about MongoDB, if you are a C # developer, you might as well take a few minutes to read this article.
First, brief introduction
MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for WEB applications.
MongoDB is a high-performance, open source, schemalless document database, which is one of the most popular NoSql databases.
MongoDB is a product between relational database and non-relational database, which is the most functional and most like relational database in non-relational database. The data structure he supports is very loose, which is similar to json's bjson format, so it can store more complex data types. The most important feature of Mongo is that the query language it supports is very powerful, and its syntax is somewhat similar to the object-oriented query language. It can almost achieve most of the functions similar to the single table query of relational database, and also supports the establishment of data indexing.
The traditional relational database is generally composed of three hierarchical concepts: database (database), table (table) and record (record). MongoDB is composed of three levels: database (database), set (collection) and document object (document). MongoDB is for tables in relational databases, but there are no concepts of columns, rows, and relationships in the collection, which reflects the characteristics of schema freedom.
Second, characteristics
It is characterized by high performance, easy to deploy, easy to use, and it is very convenient to store data. The main functional features are:
1) for collection storage, it is easy to store data of object type.
2) Free mode.
3) dynamic query is supported.
4) full indexing is supported, including internal objects.
5) query is supported.
6) replication and failure recovery are supported.
7) use efficient binary data storage, including large objects such as video, etc.
8) automatically handle fragments to support scalability at the cloud computing level.
9) support multiple languages such as RUBY,PYTHON,JAVA,C++,PHP,C#.
10) the file format is BSON (an extension of JSON).
11) can be accessed through the network.
Third, download, install and start the server
3.1) the current version of MongoDB is 2.0.4, download address: http://www.mongodb.org/downloads. Versions of various platforms are available. What I choose here is under the Windows platform.
Create a new directory E:\ mongodb and extract the downloaded package to this directory. There is a pile of .exe files under the bin folder
There are two of the most important files: Mongod.exe and Mongo.exe.
Mongod.exe is used to connect to the mongo database server, that is, the server side.
Mongo.exe is used to start MongoDB shell, that is, the client.
Other documents:
Mongodump logical backup tool.
Mongorestore logical recovery tool.
Mongoexport data export utility.
Mongoimport data Import tool.
3.3) start the server
Step 1: create a new directory to store the database files of MongoDB, namely dbpath. You can build it anywhere. I build it here in E:\ MongoDBFiles. This is for the next step.
Step 2: open the CMD window and type the following command
> e:
> cd e:\ mongodb\ mongodb-win32-i386-2.0.4\ bin
> mongod.exe-dbpath "E:\ mongodbfiles"
The-dbpath parameter value in the last command is the folder we created in the first step. This folder must be established before starting the service, otherwise an error will be reported and mongodb will not create it itself.
If the operation is successful, the following interface appears:
This interface shows us some information: for example, the process ID is 2988 and the port number is 27017.
Open a browser and enter: http://127.0.0.1:27017/
We see the following hint:
"You are trying to access MongoDB on the native driver port. For http diagnostic access, add 1000 to the port number"
At this point, the MongoDB database service has been started successfully.
Fourth, use mongo.exe to add, delete, modify and query the database
The client management tool provided by mongodb is mongo.exe.
4.1) create the database:
Double-click to open mongo.exe and the following interface appears:
The interface means that the currently connected database is test, which is what the system will create by default. Why is it "going to be created"? Because this database does not exist at this time, or it is only in memory and is not created on the physical disk. Believe it or not, there is nothing under the MongoDBFiles folder except mongod.lock. The database will not really be created until you execute the command to insert the data.
All right, let's forget about this test for a while. Now let's create a database called cnblogs.
Type the following command in the shell command window:
> the use cnblogs / / use command is used to switch the current database. If the database does not exist, a new one will be created first.
4.2) create collection and insert data
In traditional relational databases, tables are created after the library is created, but there is no concept of "tables" in mongoDB, and the corresponding concept is collection, that is, collection.
Type the following command in the shell command window:
> db.users.insert ({'name':'xumingxiang','sex':'man'})
/ / this command inserts a piece of data into the users collection. If the collection users does not exist, a new one is created and then the data is inserted, and the parameters are passed in JSON format.
Because we are going to test deleting data later, we insert another piece of data:
> db.users.insert ({'name':xiangshu','sex':'man'})
4.3) in 4.1) and 4.2 above) We created the database, created the collection, and inserted two pieces of data, so have these operations been performed successfully? Let's check it out:
Type the following command in the shell command window:
> show dbs / / Show all databases
> show collections / / displays all collections under the current database
> db.users.find () / / displays all data documents under the users collection
The shell interface is as follows:
Look at the part I marked in red. This shows that our previous operation is successful. We also see that the system assigns a unique primary key _ id to each record.
4.4) Update data
Now we are going to change the sex of the second piece of data to "women".
Type the following command in the shell command window:
> db.users.update ({'name':'xiangshu'}, {' $set': {'sex':'women'}}, upsert=true,multi=false)
Explain several parameters:
First: the conditions of the query
Second: updated fields
Third: insert if it does not exist
Fourth: whether multiple records are allowed to be modified
4.5) Delete records
We are now going to put the first record, that is, 'name' is' xumingxiang'.
Type the following command in the shell command window:
> db. Users.remove ({'name':'xumingxiang'})
We are checking 4) 5) if the two steps are successful, type the following command in the shell command window:
> db.users.find ()
From the output interface, we can see that there is only one 'name'' xiangshu' left, and its' sex' is' women', which means 4) 5) the two-step operation was successful.
4.6) Delete all records
> db.users.remove ()
4.7) Delete collection
> db.users.drop () / / returns "true" if the deletion is successful, "false" otherwise
4.8) Delete the current database
> db.dropDatabase ()
Five, more orders.
Db.AddUser (username,password) add user
Db.auth (usrename,password) sets up database connection verification
Db.cloneDataBase (fromhost) Clones a database from the target server
Db.commandHelp (name) returns the help for the command
Db.copyDatabase (fromdb,todb,fromhost) replication database fromdb--- source database name, todb--- target database name, fromhost--- source database server address
Db.createCollection (name, {size:3333,capped:333,max:88888}) creates a dataset, which is equivalent to a table
Db.currentOp () cancels the current operation of the current library
Db.dropDataBase () deletes the current database
Db.eval (func,args) run code server-side
Db.getCollection (cname) gets a collection of data. Synonym: db ['cname'] or
Db.getCollenctionNames () gets a list of the names of all data sets
Db.getLastError () returns the last error message
Db.getLastErrorObj () returns the last wrong object
Db.getMongo () gets the connection object get the server of the current 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 last error object
Db.getProfilingLevel ()
Db.getReplicationInfo () gets duplicate data
Db.getSisterDB (name) get the db at the same server as this onew
Db.killOp () stops (kills) the current operation in the current library
Db.printCollectionStats () returns the dataset status of the current library
Db.printReplicationInfo ()
Db.printSlaveReplicationInfo ()
Db.printShardingStatus () returns whether the current database is a shared database
Db.removeUser (username) Delete 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 hours offline 1 month 2 months all
Db.shutdownServer () closes the current service program
Db.version () returns the version information of the current program
Db.test.find ({id:10}) returns the dataset of the test dataset ID=10
Db.test.find ({id:10}) .count () returns the total number of data from the test dataset ID=10
Db.test.find ({id:10}) .limit (2) returns the dataset of the test dataset ID=10 the dataset starting from Article 2
Db.test.find ({id:10}) .skip (8) returns the dataset of the test dataset ID=10 from 0 to 8
Db.test.find ({id:10}) .limit (2) .skip (8) returns data from articles 2 to 8 of the dataset of the test dataset ID=1=
Db.test.find ({id:10}) .sort () returns the sorted dataset of the test dataset ID=10
Db.test.findOne ([query]) returns a piece of data that meets the criteria
Db.test.getDB () returns the name of the database to which this dataset belongs
Db.test.getIndexes () returns the index information of some datasets
Db.test.group ({key:...,initial:...,reduce:... [, cond:...]})
Db.test.mapReduce (mayFunction,reduceFunction,)
Db.test.remove (query) deletes a piece of data in the dataset
Db.test.renameCollection (newName) renames some dataset names
Db.test.save (obj) inserts a piece of data 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 index file size 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 () validates this dataset
Db.test.getShardVersion () returns the dataset shared version number
6. Comparison between MongoDB syntax and existing relational database SQL syntax.
MongoDB Syntax MySql Syntax
Db.test.find ({'name':'foobar'}) select * from test where name='foobar'
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
Db.test.find ({'ID': {$in: [25min35 in]}}) select * from test where ID in (25pence35 from test where ID in)
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 x.Sex = = "man")
}
/ / /
/ / Delete data
/ / /
Public void Delete ()
{
Var col = db.GetCollection ()
Col.Remove (x = > x.Sex = = "man")
/ or
/ find out the first record whose name value is 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 the data of the specified query condition
Var result1 = col.Find (query)
/ / query the first piece of data for the specified query condition
Var result2 = col.FindOne (query)
/ / query the data in all collections
Var result3 = col.FindAll ()
}
Ten, write a batch to make it easy to start the Mongodb server
Every time you open the Mongodb server, you have to open the CMD window. Are you tired of typing such a command over and over again? Anyway, I hate tapping dos commands and like to click with the mouse.
How can I turn on the Mongodb server with a mouse click? As you may have thought, it is done by writing a batch program. Yes, that's it. This batch process is very simple.
The full code is as follows:
@ echo
@ pause
Mongod-repair-dbpath "E:\ mongodbfiles"
Mongod-dbpath "E:\ mongodbfiles"
@ pause
Note: "mongod-repair-dbpath" E:\ mongodbfiles "is designed to solve the problem of sometimes reporting an error" Unclean shutdown detected mongodb "at startup.
Copy it to notepad, save it as a .bat file, put it in the same directory as mongod.exe, double-click it and OK it.
The above is the nature of MongoDB shared by the editor and how to install and configure it. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.