Installation and use of MongoDB under Ubuntu

Source: Internet
Author: User
Tags getmessage install mongodb mongoclient mongodb driver mongodb version relational database table

This post describes MongoDB and details the reader's installation and use of MongoDB under Ubuntu. This tutorial was tested under Ubuntu14.04.

First, MongoDB Introduction

MongoDB is a database based on distributed file storage, between relational database and non-relational database, the most abundant function of non-relational database, most like relational database. The data structure he supports is very loose and is a JSON-like Bson format, so you can store more complex data types. MONGO's biggest feature is that the query language he supports is very powerful, and its syntax is a bit like an object-oriented query language that almost implements most of the functionality of a relational database single-table query, and also supports indexing of data.

Ii. installation of MongoDB

MongoDB installation is very simple, no need to download the source files, can be installed directly with the Apt-get command.
Open terminal and enter the following command:

sudo apt-get install mongodb

As follows:

After the installation is complete, enter the following command in the terminal to view the MongoDB version:

mongo -version

The output version information indicates that the installation was successful, as follows:

Start and close the MongoDB command as follows:

service mongodb startservice mongodb stop

As follows:

The default setting MongoDB is started automatically with Ubuntu boot.
Enter the following command to see if it started successfully:

-l   #注意:-l是英文字母l,不是阿拉伯数字1

As follows:

Third, using the Mongodbshell command mode

Enter the mongo shell command mode, the default connection to the database is the test database, before you must ensure that you have started MongoDB, otherwise there will be an error, after starting to run successfully, as follows:

Common Operation Commands:

Database related
show dbs: Displays the list of databases
show collections: Displays a collection in the current database (similar to tables in a relational database table)
show users: Show All Users
use yourDB: Switch the current database to Yourdb
db.help(): Show Database Operations Command
db.yourCollection.help(): Displays the collection Action command, Yourcollection is the collection name
MongoDB does not have a command to create a database, if you want to create a "School" database, run the use School command first, then do something (such as create a clustered collection db.createCollection(‘teacher‘) ) so that you can create a database called "School". As follows:

The following is an example of a school database in which two sets teacher and student are created in the school database, and the data in the student collection is added and removed for basic operations (Set collection equals table tables in the relational database).
1. Switch to School database

#切换到School数据库。MongoDB 无需预创建School数据库,在使用时会自动创建

2. Create Collection

db.createCollection(‘teacher‘#创建一个聚集集合。MongoDB 其实在插入数据的时候,也会自动创建对应的集合,无需预定义集合

As follows:

3. Inserting data
Similar to database creation, collections are created automatically when data is inserted.
There are two ways of inserting data: Insert and save.

db.student.insert({_id:1‘zhangsan‘20#_id可选db.student.save({_id:1‘zhangsan‘22#_id可选

In both of these ways, the _id field in the inserted data is not writable, and a unique _id is automatically generated to identify this piece of data. The difference between insert and save is that when you manually insert the _id field, if _id already exists, insert does not do the action, save does the update, and if you do not add the _id field, the same effect is to insert the data. As follows:

The added data is loosely structured, and the column properties are not fixed as long as the Bson format is available, whichever is added. Once you have defined the data, you can insert more than one data at a time, as follows:

After running the above example, student has been created automatically, which also shows that MongoDB does not need to pre-define collection, collection will be created automatically after the data is inserted for the first time. As follows:

3. Find data
db.youCollection.find(criteria, filterDisplay)
Criteria: query criteria, optional
Filterdisplay: Filter Displays part of the data, such as displaying the specified column data, optional (when selected, the first parameter can not be omitted, if the query condition is empty, {} can be used as a placeholder, the following example of the third sentence)

Db.student.find ()#查询所有记录. Equivalent to: SELECT * FROM StudentDb.student.find ({sname:' Lisi '})#查询sname = Record of ' Lisi '. Equivalent to: SELECT * from student where sname= ' Lisi 'Db.student.find ({},{sname:1, Sage:1})#查询指定列sname, sage data. Equivalent to: Select Sname,sage from student. Sname:1 means that the sname column is returned, and the default _id field is returned, and you can add _id:0 (meaning not to return _id) as {sname:1, sage:1,_id:0}, and the default _id field is not returned.Db.student.find ({sname:' Zhangsan ', Sage: A})#and and conditional queries. Equivalent to: SELECT * FROM student where sname = ' Zhangsan ' and sage =Db.student.find ({$or: [{sage: A}, {sage: -}]})#or a conditional query. Equivalent to: SELECT * FROM student where sage = or sage =

The query operation is similar, here only db.student.find({sname: ‘lisi‘}) the query, as follows:

4. Modify the data
db.youCollection.update(criteria, objNew, upsert, multi )
Criteria:update query conditions, similar to those in the SQL update query
Objnew:update objects and some updated operators (such as $set ), etc., can also be understood as SQL update queries within the set.
Upsert: If there is no record of update, insert objnew,true as INSERT, default is False, do not insert.
Multi:mongodb default is False, only update the first record found, if this parameter is true, the condition is checked out all the records are updated. The default is false to modify only the first data that matches to.
Where criteria and objnew are required parameters, Upsert and multi optional Parameters
Examples are as follows:

‘lisi‘}, {$set30falsetrue#相当于:update student set sage =30 where sname = ‘lisi‘;

The operation is as follows:

5. Delete data

‘chenliu‘#相当于:delete from student where sname=‘chenliu‘

The operation is as follows:

6. Exit Shell Command mode
Enter exit or Ctrl+C exit shell command mode

Note: MongoDB is more security than the ease of use, the default is not open user rights, if you want to turn on user rights, you can refer to Ubuntu under the user rights to open MongoDB.

Java API Programming Example

First step: Download java MongoDB Driver driver jar package, Java mongodb Driver, default download directory for ~/download or ~/downloads
Step two: Open Eclipse, create a new Java Project, create a new class, and introduce the jar package that you just downloaded
Step Three: Coding implementation
Here is the source code:

ImportJava.util.ArrayList;ImportJava.util.List;ImportOrg.bson.Document;ImportCom.mongodb.MongoClient;ImportCom.mongodb.client.MongoCollection;ImportCom.mongodb.client.MongoCursor;ImportCom.mongodb.client.MongoDatabase;ImportCom.mongodb.client.model.Filters; Public  class testmongodb {    /** * @param args * *     Public Static void Main(string[] args) {Insert ();//Insert data. When you perform an insert, you can comment out the other three-sentence function call statement//find ();//Lookup Data//update ();//Updating Data//delete ();//Delete data}/** * Returns the specified collection in the specified database * @param dbname database name * @param CollectionName collection name * @return 
       * *    //mongodb does not require predefined databases and collections, which are automatically created when used     Public StaticMongocollection<document>GetCollection(String dbname,string CollectionName) {//Instantiation of a MONGO client, server address: localhost (local), port number: 27017Mongoclient mongoclient=NewMongoclient ("localhost",27017);//instantiation of a MONGO databaseMongodatabase mongodatabase = mongoclient.getdatabase (dbname);//Get a collection in the databaseMongocollection<document> collection = Mongodatabase.getcollection (CollectionName);returnCollection }/** * Insert data * /     Public Static void Insert(){Try{//Connect MongoDB, specify the connection database name, specify the connection table name. Mongocollection<document> collection= GetCollection ("Test","Student");//Instantiate a document with the contents of {sname: ' Mary ', sage:25}, and if there are other fields, you can continue appending appendDocument doc1=NewDocument ("Sname","Mary"). Append ("Sage", -);//Instantiate a document with the document content {sname: ' Bob ', sage:20}Document doc2=NewDocument ("Sname","Bob"). Append ("Sage", -); list<document> documents =NewArraylist<document> ();//Add Doc1, doc2 to the Documents listDocuments.Add (Doc1); Documents.Add (DOC2);//Insert documents into the collectionCollection.insertmany (documents); System.out.println ("Insert succeeded"); }Catch(Exception e) {System.err.println (E.getclass (). GetName () +": "+ e.getmessage ()); }    }/** * Query data * *     Public Static void Find(){Try{mongocollection<document> collection = GetCollection ("Test","Student");//Iterate through a retrieved collection of documents through a cursor//mongocursor<document> cursor= Collection.find (New Document ("Sname", "Mary")). Projection (New Documen   T ("Sname", 1). Append ("Sage", 1). Append ("_id", 0)). iterator (); Find query condition: sname= ' Mary '. Projection filter: Show sname and sage, do not display _id (_id is displayed by default)            //Query all dataMongocursor<document> cursor= Collection.find (). iterator (); while(Cursor.hasnext ())            {System.out.println (Cursor.next (). ToJson ()); }        }Catch(Exception e) {System.err.println (E.getclass (). GetName () +": "+ e.getmessage ()); }    }/** * Update data * /     Public Static void Update(){Try{mongocollection<document> collection = GetCollection ("Test","Student");//Update document to modify the document Sname= ' Mary ' to sage=22Collection.updatemany (Filters.eq ("Sname","Mary"),NewDocument ("$set",NewDocument ("Sage", A))); System.out.println ("The update is successful!" "); }Catch(Exception e) {System.err.println (E.getclass (). GetName () +": "+ e.getmessage ()); }    }/** * Delete data * /     Public Static void Delete(){Try{mongocollection<document> collection = GetCollection ("Test","Student");//Delete the first document that meets the criteriaCollection.deleteone (Filters.eq ("Sname","Bob"));//Delete all eligible documents            //collection.deletemany (Filters.eq ("sname", "Bob"));System.out.println ("Delete succeeded!" "); }Catch(Exception e) {System.err.println (E.getclass (). GetName () +": "+ e.getmessage ()); }    }}

Each time you execute the program, you can return to Shell mode to view the results. For example: After Eclipse finishes the update operation, in shell mode db.student.find() , you can view all the data for the student collection, as follows:

Installation and use of MongoDB under Ubuntu

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.