Quick start with MongoDB basic operations

Source: Internet
Author: User

1.MongoDb Introduction

MongoDB is a distributed storage-based open source database system, also known as a document database, can be stored as a document, data structure has a key-value pair (Key=>value) pair composition, the stored document is similar to the JSON object (Bson->json binary).

Features: Internal execution engine for JS interpreter, the document is stored as Bson structure, in the query, converted to JS object, and can be manipulated by the familiar JS syntax.

MongoDB and traditional database simple comparison, the biggest difference:

Traditional database: Structured data, after the table structure is fixed, the content of each row must conform to the table structure, that is, the number of columns and the same type.

Document database: Each document under a table can have its own unique structure or properties and values.

2.MongoDb installation (detailed installation steps under CENTOS7)

1) First download the MongoDB installation package:

#wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-3.4.4.tgz

2) go to the downloaded directory and unzip the MongoDB installation package into the specified directory:

#tar-XVF mongodb-linux-x86_64-rhel70-3.4.4.tgz-c/usr/local

3) Enter the extracted directory to start the MongoDB service

#cd/usr/local

Renaming a directory of MongoDB decompression

#mv mongodb-linux-x86_64-rhel70-3.4.4 MONGODB#CD MongoDB

4) Start MongoDB

#mkdir-P/home/mongodata//var/log/mongolog/#./bin/mongod--dbpath/home/mongodata/--logpath/var/log/mongolog/ Mongo.log--fork--port 27017

Start parameter Description:

--dbpath Data Storage Directory

--logpath Log Store Directory

--port Running Port

--fork Background Run

5) Connect to MongoDB via client

#./bin/mongo

Note: In some older versions, when MongoDB starts up, it takes up a lot of disk space, it may take up 3-4g space after startup, if the virtual machine's space is too big to start, but it has an option--smallfiles can reduce the start-up space to about 400M.

3.mongodb Specific Operation example

First, the introduction of MongoDB operation:

1) query all library list

>show DBS;

2) Switch database (select database to use)

>use Local;

3) Create a database

(Note: Since the MongoDB database is implicitly created without a direct way to create a database, you can switch directly to a non-existent library by using use, and the current database is created automatically when the table (collections) is created)

>use Shop

(assuming that the shop library does not exist, you can use it directly)

>db.createcollection (' user ');

(You can create a collections directly underneath a nonexistent library (or you can say create a table).)

>show DBS;

Then you go to check the library and you will find that the store shop has been created by default.

4) Create a table (collections)

>db.createcollection (' user ')

Note: tables (that is, collections) can also be created implicitly, and take the example above: if there is no goods table (collections) in the shop store, we can still insert the data using the following method

>db.goods.insert ({_id:1,name: ' Pipixia ', price:52.10});

Then we went to the shop in the library of the Table (collections), found that goods has been automatically created.

5) Insert a single document (data) into the Collections (table) (the inserted data is in JSON format)

>db.user.insert ({name: ' Zhang San ', age:18})

6) Find the contents of the Collections (table)

>db.user.find ()

7) Delete Collections (table) ()

>db.user.drop ()

8) Delete database (databases)

>db.dropdatabase ()

Second, the basic operation of MongoDB (add, delete, change, check) curd

1. Add Operation: Insert

Note: MongoDB stores documents, and so-called documents are actually JSON-formatted objects here.

1) Add a single document

>db.collectionname.insert ({sn: ' 001 ', Name: ' Xiaoming '})

2) Add a single document and specify the ID

>db.collectionname.insert ({_id:2,sn: ' 002 ', Name: ' Xiaohong '})

3) Add multiple documents (because JSON is an object, JS has the concept of an array, just put multiple objects in the array)

>db.collectionname.insert ([{sn: ' 003 ', ' name ': ' Zhangfei '},{SN: ' 004 ', ' name ': ' Guanyu '},{SN: ' 004 ', ' name ': ' Liubei ‘}])

2. Delete operation: Remove

Syntax: db.collectionName.remove (query expression, options)

Option refers to {Justone:true/false}, whether to delete a row, false by default

Attention:

1. The query expression is still a JSON object

2. The row to which the query expression matches is deleted

3. If there is no query expression, all documents in collections will be deleted

1) Delete the specified JSON document (object in JSON format)

Example: Delete a JSON object document with the SN attribute value 002 in the CollectionName table

>db.collectionname.remove ({sn: ' 002 '})

2) If the query expression is empty, the following

>db.collectionname.remove ()

All documents in the library are deleted, use caution

3) If we want to delete a row of data that matches a query expression, you can use the options feature mentioned above, such as

>db.collectionname.remove ({"Name": "Zhangsan"},true)

Only one of the document data that has the name matching Zhangsan will be deleted

3. Change operation: Update

Syntax: db.collectionName.update (query expression, new value, options)

1) The query expression refers to who needs to be modified, the new value refers to the change, the option refers to the optional parameters

For example:

>db.collectionname.update ({name: ' Zhangfei '},{name: ' Zhangfeifei '})

Look at the change results

>db.collectionname.find ()

You will find the ID and Name column are left in the modified document, and the SN column is missing.

Cause: The new document replaces the old document directly, rather than modifying the

2) But we can use $set to specify that a column be modified

>db.collectionname.update ({name: ' Guanyu '},{$set: {name: ' Guanyunchang '}})

An assignment expression when modified

$set Modify the value of a column

$unset Delete a column

$rename Rename a column

$inc increase the value of a column

3) to a complex update operation

Insert a piece of data first

>db.collectionname.insert ({name: ' Caocao ', Age:40,sex: ' m ', addr: ' Wei ')

Modify this data

>db.collectionname.update ({name: ' Caocao '},{$set: {name: ' Caoaman '}, $unset: {addr:1}, $rename: {sex: ' Gender '},$ INC:{AGE:10}})

4) The function of the third optional parameter option:

{Upsert:true/false,multi:true/false}

Upsert refers to a row that does not have a match and is inserted directly into the row. (similar to replace in MySQL)

For example:

>db.collectionname.update ({_id:100},{name: ' Liubei '},{upsert:true})

If there is no document with a _id of 100, insert the document directly.

Note: If there are no documents with _id 100 and no Upsert optional parameters, then the new operation will not affect the document in the table.

Multi means to change the line.

That is, if the query expression matches to multiple rows, only one row is changed by default, and you need to use this option if you want to modify multiple rows.

For example:

>db.collectionname.update ({sex: ' m '}, $set: {sex: ' W '},{multi:true})

Changes all sex=m documents in the CollectionName to Sex=w

4. Check operation: Find,findone

Syntax: db.collection.find (query expression, query column)

For example:

1) Querying all documents

>db.collectionname.find ()

2) Query the sex Attribute (column) of all documents

>db.collectionname.find ({},{sex:1})

3) Query the sex property of all documents without querying the _ID property

>db.collectionname.find ({},{sex:1,_id:0})


Note: No matter whether adding or deleting changes can not be separated from a query expression, the above examples are relatively simple to get started operation



This article is from the "Omcloud" blog, make sure to keep this source http://10616534.blog.51cto.com/10606534/1939384

Quick start with MongoDB basic operations

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.