Install and use mongodb

Source: Internet
Author: User
Tags robomongo

Install and use mongodb

1. Install and start MongoDB

Widndows and linux are basically the same

1. Download the database,

Mongodb-linux-x86_64-ubuntu1404-3.0.3.tgz: linux

2. decompress the file and place it in a proper location.

Tar-vxf mongodb-linux-x86_64-ubuntu1404-3.0.3.tgz

Music mongodb-linux-x86_64-ubuntu1404-3.0.3/usr/local/mongodb

3. create necessary folders and files

Database Folder:/usr/local/mongodb/data/db

Log File:/usr/local/mongodb/data/log/mongodb. log

After the process is complete, remember to authorize the folder and file. Otherwise, the service cannot be opened.

4. Set the database location and log location and enable the Service:

Bin (linux)->./mongod -- port 27017 -- dbpath/usr/local/mongodb/data/db -- logpath/usr/local/mongodb/data/log/mongodb. log

In linux, pay attention to file and file read/write permissions. Of course, there are many parameters to enable the service, not to list them one by one.

Bin (win)-> mongod -- port 27017 -- dbpath "D: \ Program Files \ MongoDB \ Server \ 3.0 \ data \ db" -- logpath "D: \ Program Files \ apsaradb for MongoDB \ Server \ 3.0 \ data \ log \ apsaradb for MongoDB. log"

5. Connect to the database:

Bin (linux)->./mongo

Bin (win)-> cmd.exe

Note: creating folders and log files in windows does not describe the operation process. another point is that after the service is started, do not close the Service Startup interface or press Ctrl + C. A new window is required when you connect to the database. of course, the service can also run in the background. run the following command in the background: nohup. /mongod -- port 27017 -- dbpath/usr/local/mongodb/data/db -- logpath/usr/local/mongodb/data/log/mongodb. log &

6. Connect to mongodb through a graphical Client

In windows, many options are available, including robomongo and zoovue. in linux, robomongo is available. go to the official website to download and install it. the advantage of robomongo is that you can directly run shell commands in the software, and there are prompts. The advantage of javasvue is that the query section is clear and you do not need to run a complete and complex shell command.

7. Other mongodb Script Commands

Backup: mongodump/recovery: mongorestore

Import data: Export Import-d dbName-c collectionName -- file filePath; there are many other optional parameters

Export data: Export export-d dbName-c collectionName-o filePaht; there are many other optional parameters

By default, imported and exported data is in json format. To adapt to data interaction with other databases, you can select the file to be imported and exported as the CVS file.

Ii. simple use of MongoDB

Using mongoDB for CRUD operations is to execute the shell statement of the response, so it is actually the use of shell statements. First, you need to understand several simple objects of mongoDB: db, collection, document.

Db: a database object, equivalent to a database object in a relational database.

Collection: A collection object, equivalent to a table in a relational database.

Document: a document object, equivalent to a record row in a table in a relational database.

1. database operations:

> Db; // view the database currently in use

> Show dbs; // display all databases

> Use dbName; // use a database. If the database does not exist, create a database. This command is also used to create a database.

> Db stats (); // view the current status of the database

> Db. dropDatabase (); // Delete the current database

2. operations on the set:

> Db. createCollection (collectionName, option); // collectionName is the Set Name and option is an optional parameter, including the database size.

> Db. collectionName. drop (); // delete a set. collectionName indicates the Set Name.

3. Document operations:

> Db. collectionName. insert (document); // insert data to the set. document (Json) is a json object or array.

> Db. collectionName. find (condition); db. collectionName. findOne (); db. collectionName. find (). pertty ();

// Query records. The condition (Json) is a filter condition. If no condition is added, all records are queried. Pertty () indicates that the output format is optimized. find has a lot of detailed processing details.

> Db. collectionName. update (condition, updateDate); // update record, where condition (Json) is in the filter condition json format. UpdateDate is the data to be updated.

//> Db. mycol. update ({"a": 1 },{$ set: {"B": "B "}}); change the B Field of the object whose field a is 1 in the mycol set to "B"

> Db. collectionName. remove (condition, justOne); // delete a record. Here, condition (Json) is a filtering condition, and justOne (boolean) indicates whether to delete only the first record. If no record is added, the set is cleared.

> Db. collectionName. find (). skip (num). limit (num); // query by page. num (Number) indicates the start page and size of each page.

> Db. collectionName. find (condition, {Key: isHead}); // projection. The second json field indicates whether a field is hidden, and isHead (0/1) indicates

> Db. collectionName. find (). sort ({Key: upOrDown}); // sort the results. The key is the sort keyword, And the upOrDown (-1/1) indicates whether the order is ascending or descending.

> Db. collectionName. ensureIndex ({key: upOrDown}); // create an index. The key is the index field, and the upOrDown (-1/1) indicates whether the index is in ascending or descending order.

> Db. collectionName. aggregate (options); // clustering function. options (JsonArray) is optional.

// Db. mycol. aggregate ([{$ group: {field: "$ by_field", total: {$ sum: 1 }}]); // grouping by by_field field, show field and total columns

 

Iii. Java operations on MongoDB:

When operating mongo in java, you must first support the jar package. If you use mave, the dependencies are as follows:

<dependency>    <groupId>org.springframework.data</groupId>    <artifactId>spring-data-mongodb</artifactId>    <version>1.3.0.RELEASE</version></dependency><dependency>    <groupId>org.mongodb</groupId>    <artifactId>mongo-java-driver</artifactId>    <version>2.11.1</version></dependency>

Several Basic java objects are described as follows:

Mongo: database connection object

Mongo monge = new Mongo ("localhost", portl );

DB: database object

DB db = monge. getDB ("dbName ");

DBCollection: Collection object

DBCollection collection = db. getCollection ("collectionName ");

BasicDBObject: Document Object

BasicDBObject basicDBObject = new BaseDBObject ();

DBObject: superclass of the Document Object

DBObject dbObject = (DBObject) JSON. parse ("json ");

DBCursor: cursor During Operation

DBCursor cursor = collection. find ();

DBCursor cursor = collection. find ("conditionJson ");

The Code is as follows:

@ Testpublic void testMongo () throws UnknownHostException {Mongo mongo = new MongoClient ("127.0.0.1", 27017); // connect the database to DB db = mongo. getDB ("test"); // database object DBCollection coll1 = db. getCollection ("coll1"); // obtain the collection object DBCollection coll2 = db. createCollection ("coll2", null); Set <String> collSet = db. getCollectionNames (); DBObject doc1 = new BasicDBObject ("a", 1); // database document object doc1.put ("B", "B"); DBObject doc2 = (DBObject) JSON. parse ("{\" a \ ": 2, \" B \ ": \" B \ "}"); // insert data coll1.insert (doc1, doc2 ); // modify the data DBObject update = (DBObject) JSON. parse ("{\" a \ ": 2, \" B \ ": \" updateB \ "}"); coll1.update (new BasicDBObject ("a", 2 ), update, true, false); Map <String, Object> map = new HashMap <String, Object> (); map. put ("c", "updateC"); map. put ("d", 4); coll1.update (new BasicDBObject ("a", 1), new BasicDBObject (map); // query the Document Object DBObject ref = (DBObject) JSON. parse ("{\" B \ ": \" updateB \ "}"); DBCursor cursor = coll1.find (ref); while (cursor. hasNext () {DBObject obj = cursor. next (); int valuea = (Integer) obj. get ("a"); String valueb = (String) obj. get ("B"); System. out. println (valuea + "-" + valueb); System. out. println (obj);} // delete data coll1.remove (new BasicDBObject ("a", 1); coll1.drop (); // clear data}


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.