MongoDB Knowledge Point Collation (i)

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

Brief introduction

    • 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
    • View official website

MongoDB 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)

Basic operations

    • MongoDB stores data as a document, and data structures are composed of key-value (Key=>value) pairs
    • MongoDB documents are similar to JSON objects, and field values can contain other documents, arrays, document arrays
    • Installing the Manage MongoDB environment
    • Complete management of databases and collections
    • Data additions, modifications, deletions, queries

Noun

SQL Terminology / Concept

MongoDB Terminology / Concept

explain / Description

Database

Database

Database

Table

Collection

Database Tables/Collections

Row

Document

Data record lines/documents

Column

Field

Data fields/Fields

Index

Index

Index

Table joins

Table connection, MongoDB not supported

Primary key

Primary key

Primary key, MongoDB automatically sets the _id field as the primary key

    • 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 ': ' Man '}

    • 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 ': ' Man '}

{' name ': ' Huangrong ', ' Age ': 18}

{' book ': ' Shuihuzhuan ', ' heros ': ' 108 '}

    • Database: is a collection of physical containers that can contain multiple documents in a database
    • A server typically has multiple databases
    • Download MongoDB version, two points note
    • According to industry rules, even a stable version, such as 1.6.X, odd for the development version, such as 1.7.X
    • 32bit MongoDB can only store 2G of data, 64bit there is no limit
    • To the official website, select the appropriate version to download
    • Extract
Installation

TAR-ZXVF mongodb-linux-x86_64-ubuntu1604-3.4.0.tgz

    • Move to the/usr/local/directory

sudo mv-r mongodb-linux-x86_64-ubuntu1604-3.4.0//usr/local/mongodb

    • To add an executable file to a path path

Export Path=/usr/local/mongodb/bin: $PATH

Management MONGO

    • Configuration file in/etc/mongod.conf
    • Default Port 27017
    • Start

sudo service Mongod start

    • Stop it

sudo service Mongod stop

    • Using Terminal connections
    • This shell is the client of MongoDB, but also a JS compiler.

Mongo

    • Command

DB View Current database name

Db.stats () View current database information

    • Terminal Exit connection

Exit

or CTRL + C

    • Gui:robomongo, unzip and locate the running program in the bin directory
    • The interface is as follows:

Database switchover

    • View the current database name

Db

    • View all database names
    • List all databases that are physically present

Show DBS

    • Switch database
    • If the database does not exist, point to the database but not create it until the database is created when the data is inserted or the collection is created

Use database name

    • The default database is test, and if you do not create a new database, the collection will be stored in the test database

Database Delete

    • Delete the currently pointing database
    • Do nothing if the database does not exist

Db.dropdatabase ()

Collection creation

    • Grammar

Db.createcollection (name, options)

    • Name is the names of the collections to be created
    • Options is a document that specifies the configuration of the collection
    • Options?? The parameter is optional, so only the specified collection name is required. The following is a list of options you can use:
    • Example 1: No limit on collection size

Db.createcollection ("Stu")

    • Example 2: Limit the size of a collection, and later learn to insert a statement to see the effect
    • Parameter capped: The default value of false means that no upper bound is set and a value of TRUE indicates an upper limit
    • 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, the previous data is overwritten, in bytes

Db.createcollection ("Sub", {capped:true, size:10})

View a collection of current databases

    • Grammar

Show collections

Delete

    • Grammar

Db. Collection name. Drop ()

Data type

    • The following table is a few of the data types commonly used in MongoDB:
    • Object ID: Document ID
    • String: Strings, most commonly used, must be valid UTF-8
    • Boolean: Stores a Boolean value, True or False
    • Integer: Integers can be either 32-bit or 64-bit, depending on the server
    • Double: Storing floating-point values
    • Arrays: Array or list, multiple values stored to a key
    • Object: Used for embedded documents, i.e. a value of one document
    • NULL: Store null value
    • Timestamp: Time stamp
    • Date: The UNIX time format that stores the current date or time

Object ID

    • Each document has a property that is _id, guaranteeing the uniqueness of each document
    • You can set _id to insert the document yourself.
    • If not provided, MongoDB provides a unique _id for each document, with a type of Objectid
    • Objectid is a 12-byte hexadecimal number
    • The first 4 bytes are the current timestamp
    • Next 3 bytes of machine ID
    • The next 2 bytes in MongoDB's service process ID
    • The last 3 bytes are simple increment values

Insert

    • Grammar

Db. Collection name. Insert (document)

    • When inserting a document, MongoDB assigns a unique objectid to the document if the _ID parameter is not specified
    • Example 1

Db.stu.insert ({name: ' GJ ', gender:1})

    • Example 2

s1={_id: ' 20160101 ', Name: ' HR '}

S1.gender=0

Db.stu.insert (S1)

Simple query

    • Grammar

Db. Collection name. Find ()

Update

    • Grammar

Db. Collection name. Update (

<query>,

<update>,

{multi: <boolean>}

)

    • Argument query: Query condition, similar to the where part of SQL statement update
    • Parameter update: update operator, similar to the set part of SQL statement update
    • Parameter multi: optional, default is False, indicates that only the first record found is updated, and a value of TRUE indicates that all documents that meet the criteria are updated
    • Example 3: Full document Update

Db.stu.update ({name: ' hr '},{name: ' MNC '})

    • Example 4: Specifying property updates via the operator $set

Db.stu.insert ({name: ' hr ', gender:0})

Db.stu.update ({name: ' hr '},{$set: {name: ' Hys '}})

    • Example 5: Modifying multiple matches to the data

Db.stu.update ({},{$set: {gender:0}},{multi:true})

Save

    • Grammar

Db. Collection name. Save (document)

    • Modified if the document's _id already exists, add if the document's _id does not exist
    • Example 6

Db.stu.save ({_id: ' 20160102 ', ' name ': ' YK ', gender:1})

    • Example 7

Db.stu.save ({_id: ' 20160102 ', ' name ': ' Wyk '})

Delete

    • Grammar

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, delete only one, default false, means delete multiple
    • Example 8: Delete Only the first one that matches

Db.stu.remove ({gender:0},{justone:true})

    • Example 9: Delete all

Db.stu.remove ({})

about the size The example

    • Example 10
    • Create a Collection

Db.createcollection (' Sub ', {capped:true,size:10})

    • Insert First database query

Db.sub.insert ({title: ' Linux ', count:10})

Db.sub.find ()

    • Insert Second database query

Db.sub.insert ({title: ' Web ', count:15})

Db.sub.find ()

    • Inserting a third database query

Db.sub.insert ({title: ' SQL ', Count:8})

Db.sub.find ()

    • Insert Fourth database query

Db.sub.insert ({title: ' Django ', Count:12})

Db.sub.find ()

    • Insert Fifth database query

Db.sub.insert ({title: ' Python ', count:14})

Db.sub.find ()

Data query

Basic Query

    • Method Find (): Query

Db. Collection name. Find ({conditional document})

    • Method FindOne (): Query, return only the first

Db. Collection name. FindOne ({conditional document})

    • Method Pretty (): Formatting the result

Db. Collection name. Find ({conditional document}). Pretty ()

Comparison operators

    • equals, default is equal to judgment, 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 for students with names equal to ' GJ '

Db.stu.find ({name: ' GJ '})

    • Example 2: Query for students older than or equal to 18

Db.stu.find ({age:{$gte: 18}})

logical operators

    • Queries can have multiple conditions, and multiple conditions need to be connected by logical operators
    • Logic and: The default is the relationship between logic and
    • Example 3: A student with an age greater than or equal to 18 and a gender of 1

Db.stu.find ({age:{$gte: 18},gender:1})

    • Logic or: Using $or
    • Example 4: A student with an age greater than 18, or a gender of 0

Db.stu.find ({$or: [{age:{$gt: 18}},{gender:1}]})

    • Use with AND and OR
    • Example 5: A student whose age is greater than 18 or sex 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 range
    • Example 6: Query for students aged 18 and 28

Db.stu.find ({age:{$in: [18,28]}})

Support for regular expressions

    • Write regular expressions using//or $regex
    • Example 7: Inquiring the student surnamed Huang

Db.stu.find ({name:/^ yellow/})

Db.stu.find ({name:{$regex: ' ^ Yellow '}}})

Custom queries

    • Use $where to write a function that returns the data that satisfies the condition
    • Example 7: Querying for students older than 30

Db.stu.find ({$where: function () {return this.age>20}})

Limit

    • Method Limit (): Used to read a specified number of documents
    • Grammar:

Db. Collection name. Find (). Limit (number)

    • The number of the parameter indicates how many bars to get the document
    • Displays all documents in the collection if no parameters are specified
    • Example 1: Query 2 Student Information

Db.stu.find (). Limit (2)

Skip

    • Method Skip (): Used to skip a specified number of documents
    • Grammar:

Db. Collection name. Find (). Skip (number)

    • The number of the parameter indicates the count of skipped records, the default value is 0
    • Example 2: Querying student information starting with 3rd

Db.stu.find (). Skip (2)

Used together

    • Method Limit () and skip () can be used together, in order of precedence
    • Create a data set

for (i=0;i<15;i++) {Db.t1.insert ({_id:i})}

    • Query 5th to 8th data

Db.stu.find (). Limit (4). Skip (5)

Or

Db.stu.find (). Skip (5). Limit (4)

Projection

    • In the returned results of the query, select only the necessary fields instead of selecting the entire field of a document
    • such as: A document has 5 fields, need to display only 3, projected 3 of the fields can be
    • Grammar:
    • parameter is field and value, value 1 indicates display, value 0 does not display

Db. Collection name. Find ({},{field name: 1,...})

    • For fields that need to be displayed, set to 1, not set to not display
    • Special: For _id columns default is displayed, if not displayed need to explicitly set to 0
    • Example 1

Db.stu.find ({},{name:1,gender:1})

    • Example 2

Db.stu.find ({},{_id:0,name:1,gender:1})

Sort

    • Method sort (), which is used to sort the result set
    • Grammar

Db. Collection name. Find (). Sort ({field: 1,...})

    • Parameter 1 is in ascending order
    • Parameter-1 is in descending order
    • Example 1: Descending according to sex, and then ascending according to age

Db.stu.find (). Sort ({gender:-1,age:1})

Number of statistics

    • Method count () is used to count the number of document bars in the result set
    • Grammar

Db. Collection name. Find ({condition}). Count ()

    • can also be associated with a

Db. Collection name. Count ({condition})

    • Example 1: Statistics on the number of males

Db.stu.find ({gender:1}). Count ()

    • Example 2: Number of males with a statistical age greater than 20

Db.stu.count ({age:{$gt: 20},gender:1})

Eliminate duplicates

    • Method Distinct () to de-weight the data
    • Grammar

Db. Collection name. Distinct (' Redo field ', {condition})

    • Example 1: Finding gender older than 18 (de-weight)

Db.stu.distinct (' Gender ', {age:{$gt: 18}})

MongoDB Knowledge Point collation (i)

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.