Database--mongodb

Source: Internet
Author: User
Tags findone logical operators mongodb server


about MongoDB
    • MongoDB is a NoSQL database based on Distributed file storage
    • Written by the C + + language, stable and high performance
    • Designed to deliver scalable, high-performance data storage solutions for WEB applications
features
    • Mode freedom: You can store documents of different structures in the same database
    • Collection-oriented storage: The format for storing JSON-style files
    • Full index support: Index any property
    • Replication and high availability: Supports data replication between servers, and supports replication between master-slave mode and server. The primary purpose of replication is to provide redundancy and automatic failover
    • Automatic sharding: Supports cloud-scale scalability: auto-sharding supports level DB clusters, adding additional machines dynamically
    • Rich query: Support rich query expression, query instructions using JSON form of tags, can easily query the document embedded objects and arrays
    • Fast in-place updates: The query optimizer parses query expressions and generates an efficient query plan
    • Efficient traditional storage: supports binary data and large objects (such as photos or pictures)
noun




    • Three elements: Databases, collections, documents
      • A collection is a table in a relational database
      • The document corresponds to a row in the relational database
    • A document is an object, consisting of key-value pairs, which is an extended bson form of JSON

{‘Name’: ‘guojing’, ‘gender’: ‘male’}
Collection: Similar to a table in a relational database, storing multiple documents, the structure is not fixed, such as the following documents can be stored in a collection
{‘Name’: ‘guojing’, ‘gender’: ‘male’}
{‘Name’: ‘huangrong’, ’age’: 18}
{‘Book’: ‘shuihuzhuan’, ’heros’: ‘108’}
Database: is a collection of physical containers, a database can contain multiple documents
A server usually has multiple databases
installation
Go to the official website, choose the appropriate version to download
Unzip
tar -zxvf mongodb-linux-x86_64-ubuntu1604-3.4.0.tgz
Move to / usr / local /
sudo mv -r mongodb-linux-x86_64-ubuntu1604-3.4.0 / / usr / local / mongodb
Add executable to PATH
export PATH = / usr / local / mongodb / bin: $ PATH
management
Configuration file in /etc/mongod.conf
Default port 27017

start up

sudo service mongod start
stop
sudo service mongod stop
Connect using terminal
This shell is the client of mongodb and also a js compiler
mongo
command
db view the current database name
db.stats () View the current database information
Terminal exit connection
exit
Or ctrl + c
type of data
Object ID: Document ID
String: string, most commonly used, must be valid UTF-8
Boolean: stores a Boolean value, true or false
Integer: The integer can be 32-bit or 64-bit, depending on the server
Double: stores floating point values
Arrays: arrays or lists, storing multiple values into one key
Object: for embedded documents, that is, one value for one document
Null: stores Null values
Timestamp: timestamp
Date: UNIX time format that stores the current date or time
object id
Each document has an attribute, _id, which guarantees the uniqueness of each document
You can set the _id to insert the document yourself
If not provided, then MongoDB provides a unique _id for each document of type objectID
objectID is a 12-byte hexadecimal number
The first 4 bytes are the current timestamp
Next 3 bytes of machine ID
MongoDB server process id in the next 2 bytes
The last 3 bytes are simple increment values
MongoDB operations 1. Database operations
View the current database name

db
List all databases that physically exist

show dbs
Switch the database, if the database does not exist, point to the database, but do not create it, the database is not created until the data is inserted or the collection is created

use database name
Note: The default database is test. If you do not create a new database, the collection will be stored in the test database.

Delete the database currently pointed to, if the database does not exist, do nothing

db.dropDatabase ()
Set operations
Create collection:

db.createCollection (name, options)
name is the name of the collection to be created
options is a document that specifies the configuration of the collection
The option ?? parameter is optional, so only the specified collection name is required.
Example 1: Unlimited collection size

db.createCollection ("stu")
Example 2: Limit the size of the collection, you can view the effect after learning to insert statements later

Parameter capped: The default value is false to indicate that no upper limit is set, and the value of true indicates that the upper limit is set
Parameter size: When the capped value is true, you need to specify this parameter, which indicates the upper limit size. When the document reaches the upper limit, it will overwrite the previous data in bytes
db.createCollection ("sub", {capped: true, size: 10})
View all collections of the current database:

show collections
Delete collection:

db.collection name.drop ()
3.Data manipulation
increase

db.collection name.insert (document)
Note: When inserting a document, if you do not specify the _id parameter, MongoDB will assign a unique ObjectId to the document

example 1

db.stu.insert ({name: ‘gj’, gender: 1})
Example 2

s1 = {_ id: ‘20160101’, name: ‘hr’}
s1.gender = 0
db.stu.insert (s1)
delete

db.collection name.remove (<query>, (justOne: <boolean>))
Parameter query: optional, the condition of the deleted document
Parameter justOne: optional, if set to true or 1, only one will be deleted, default is false, which means to delete multiple
Example 3: Only delete the first match

db.stu.remove ({gender: 0}, {justOne: true})
Example 4: Delete all

db.stu.remove ({})
change

db.collection name.update (<query>, <update>, (multi: <boolean>))
Parameter query: query conditions, similar to where part of the sql statement update
Parameter update: update operator, similar to the set part of the sql statement update
Parameter multi: optional, default is false, which means that only the first record found is updated, and a value of true means that all documents that meet the conditions are updated
Example 5: Full Document Update

db.stu.update ({name: ‘hr‘}, {name: ‘mnc‘})
Example 6: Specify property update through operator $ set

db.stu.insert ({name: ‘hr’, gender: 0})
db.stu.update ({name: ‘hr‘}, {$ set: {name: ‘hys‘}})
Example 7: Modify multiple matching data

db.stu.update ((), {$ set: {gender: 0}}, {multi: true})
4, check the basic query
Method find (): query

db.collection name.find ((conditional document))
Method findOne (): query, return only the first one

db.collection name.findOne ((conditional document))
Method pretty (): Format the result

db.collection name.find ((conditional document)). pretty ()
Comparison operator
Equal, default is equal to judge, no operator
Less than $ lt
Less than or equal to $ lte
Greater than $ gt
Greater than or equal to $ gte
Not equal to $ ne
Example 1: Query students whose name is equal to 'gj'

db.stu.find ({name: ‘gj‘})
Example 2: Query students aged 18 or above

db.stu.find ({age: {$ gte: 18}})
Logical Operators
There can be multiple conditions when querying, and multiple conditions need to be connected by logical operators
Logical AND: The relationship between logical AND by default
Example 3: Query students whose age is greater than or equal to 18 and whose gender is 1

db.stu.find ({age: {$ gte: 18}, gender: 1})
Example 4: Query students whose age is greater than 18 or whose gender is 0 (logical OR: use $ or)

db.stu.find ({$ or: [{age: {$ gt: 18}}, {gender: 1}]})
Example 5: Query students whose age is greater than 18 or whose gender is 0, and the student's name is gj

db.stu.find ({$ or: [{age: {$ gte: 18}}, {gender: 1}], name: ‘gj‘})
Range operator
Use "$ in", "$ nin" to determine if it is within a certain range
Example 6: Query students aged 18 and 28

db.stu.find ({age: {$ in: [18,28]}})
Supports regular expressions
Write regular expressions using // or $ regex
Example 7: Query the student with the last name of Huang

db.stu.find ({name: / ^ 黄 /})
db.stu.find ({name: {$ regex: ‘^ 黄‘}}})
Custom query
Write a function after $ where to return data that meets the conditions
Example 7: Query students older than 30

db.stu.find ({$ where: function () {return this.age> 20}})
5.Limit and Skip
limit () method: used to read a specified number of documents

db.collection name.find (). limit (NUMBER)
Parameter NUMBER indicates the number of documents to be obtained
If no parameter is specified, all documents in the collection are displayed
Example 1: Query 2 student information

db.stu.find (). limit (2)
skip () method: used to skip a specified number of documents

db.collection name.find (). skip (NUMBER)
The parameter NUMBER indicates the number of records skipped. The default value is 0.
Example 2: Querying student information starting from Article 3

db.stu.find (). skip (2)
 

The methods limit () and skip () can be used together, in no particular order

 

for (i = 0; i <15; i ++) {db.t1.insert ({_ id: i})}
Query the 5th to 8th data

db.stu.find (). limit (4) .skip (5)
or
db.stu.find (). skip (5) .limit (4)
6.Projection
In the returned results of the query, only the necessary fields are selected instead of the entire field of a document. The parameters are fields and values. A value of 1 indicates display and a value of 0 does not display.

For example: a document has 5 fields, only 3 of them need to be displayed, and 3 of them can be projected

db.collection name.find ((), (field name: 1, ...))
Special: The _id column is displayed by default. If it is not displayed, it must be explicitly set to 0.

example 1

db.stu.find ((), {name: 1, gender: 1})
Example 2

db.stu.find ((), {_ id: 0, name: 1, gender: 1})
Sorting
Method sort () to sort the result set

db.collection name.find (). sort ((field: 1, ...))
Parameter 1 is in ascending order
Parameter -1 is in descending order
Example 1: descending order according to gender and ascending order according to age

db.stu.find (). sort ((gender: -1, age: 1))
8. Statistics
The method count () is used to count the number of documents in the result set.

db.collection name.find ((condition)). count ()
You can also directly count the number of documents in the collection

db.collection name.count ((condition))
Example 1: Count the number of boys

db.stu.find ({gender: 1}). count ()
Example 2: Counting the number of boys older than 20

db.stu.count ((age: {$ gt: 20}, gender: 1})
Eliminate duplicates
Method distinct () deduplicates the data

db.collection name.distinct ('Duplicate field', {condition))
Example 1: Find genders older than 18 (duplicate)

db.stu.distinct (‘gender’, {age: {$ gt: 18}})
 

Database-MongoDB

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.