Linux under the terminal command of MongoDB set up, insert, delete, modify, query

Source: Internet
Author: User
Tags logical operators

  client:  
connecting server:
MONGO
View parameters:
MONGO--help
exit MONGO Service:
exit or Ctr + C
View the database currently in use (the test database is used by default after login):
Span style= "font-size:18px" > db
View all databases (databases created physically): Br> show dbs
switch database (use non-existent library in memory Pro The database is created automatically when the collection file is created):
Use library name
Delete the currently used database (do nothing if the database does not exist):
Db.dropdatabase ()
Collection Command:
Create a collection (Coorey in use):
db.createcollection (set name [, Options])//option can be omitted

Create an unrestricted-size collection stu:
db.createcollection ("Stu")

Create a limited-size collection stu:
db.createcollection ("Stu", {capped:true,size:10})
//stu for the name of the collection
//capped True to limit the total amount of data to false without restriction, false by default
//size:10 represents a maximum of 10 bytes of data, and if size is less than 256, 256 caps will be created by default
//If the deposit data exceeds the capacity limit, the first inserted data will be eliminated

to view the collection of the current database:
Show Collections

To delete a collection:
db. Collection name. Drop ()

data types commonly used by MongoDB:
ObjectID:
the data type for which the key is _id. Is the document ID, each document has this attribute, the default primary key, which guarantees that each document is unique
You can specify the value of the _id yourself, and if you do not specify, MongoDB will maintain it itself
Objectid is a 12-byte hexadecimal number:
the first 4 bytes are the current timestamp
the next 3 bytes are the machine ID
the next 2 bytes are the service process ID of MongoDB
the last 3 bytes are self-increment
String:
string, the most commonly used data type, must you be the Utf-8 type
Boolean:
Store Boolean value TRUE or False
Integer:
integer type, which can be either 32-bit or 64-bit compatible with the operating system
Double:
floating-point data type.
Arrays:
array or list, multiple values are saved to a key
Object:
the numeric type of the document used for the embedded document
Null:
storing null values
Timestamp:
Timestamp , representing the number of seconds since 1970-1-1
Date:
time, storing the current date or Unix time format.
Create Time Type data: New data ("YYYY-MM-DD")




operation of the data:

1 inserting data:
db. Collection name. Insert (document)

If you don't specify _id, MongoDB helps us maintain
Example: Db.stu.insert ({name: "haha", gender:1})

You can also specify _id
For example: Db.stu.insert ({_id: ' 20171221 ', Name: "Haha", gender:1})

2 Modifying Data:
2.1 Replacement Modifications:
db. Collection name. Update (
<query>,//Condition
<update>,//Replace qualified documents with this document to update
{multi:<boolean>}//optional parameter default false
//multi to False indicates that only the first qualifying data is updated
//multi to True means all data is updated
)

For example: Change the name of the age of 18 to the old horse and modify only the first one.
Db.stu.update (
{age:18},//condition, age is 18 years old data
{name: "Old Horse"}//This document will be replaced by a qualified document to make updates, other key value pairs will be lost, leaving only the name
///Multi default false indicates that only the first matching condition is updated
//{Multi:true} indicates that all eligible data is updated
)

2.2 Specify key-value pairs to modify, not replace: $set: {}
For example: All 18-year-olds change their names to old horses, other key-value pairs do not replace
Db.stu.update (
{age:18},//Condition
{&set{name: "Old Horse"}},//Specify key-value pairs to modify without losing key-value pairs
{Multi:true}//All eligible data modified
)

2.3 Save (if the document's _id does not exist, create a new one, if present, modify it):
db. Collection name. Save (document)
For example: Db.stu.save ({_id: ' 20160102 ', ' name ': ' YK ', gender:1})

2.4 Delete
db. Collection name. Remove (
<query>,//required parameter, delete condition
{justone:<boolean>}//Optional Parameters
//justone default False, representing the deletion of all eligible documents
//justone set to True to delete the first qualifying document
)

For example:
Delete all Documents
Db.stu.remove ({])//condition is a required parameter, all delete to pass in empty {}
Delete a student aged 18 and delete only one
db.stu.remove ({age:18},{justone:true})

3 Data Query
Basic Query Find ():
db. Collection name. Find ({condition})//query all
db. Collection name. FindOne ({condition})//query one
db. Collection name. Find ({condition}). Pretty ()//format query Results

Example: Querying all data
db.stu.find ({})//query all data
db.stu.find ({age:18}). Pretty ()//formatted output with age 18

3.1 comparison operators:
equals: Default equals no special operator
smaller than: &lt less than
less than equals: &lte lesser than equal
greater than: &gt greater than
greater than or equal to: &gte greater than equal
not equal to: &ne Not equal

For example: query for students older than 18:
db.stu.find ({age:{&gt:18}})
3.2 logical operators:
logic and: The default is the relationship
Logical OR: $or {condition}

For example: query for students older than 18 and gender 1
db.stu.find ({age:{&gt:18}, gender:1})
For example, a student who is older than 18 or has a gender of 0
Db.stu.find ($or {age:{&gt:18},gender:0})

logical OR logical and used together:
The query age is greater than 18 or the name is Guo Jing, and the gender is 1
Db.stu.find ($or {age:{&gt:18},name: "Guo Jing"},gender:1)

3.3 Range Operators:
$in: [] in which:
The age is 18 or 28 of the students:
Db.find ({age:{$in: [18,28]}})
$nin: [] not in it
The age is not 18 or 28 of students:
Db.find ({age:{$nin: [18,28]}})

3.4 Regular Expression matches "/reg/" or regex: "Reg":
for students surnamed Huang:
Db.stu.find ({name: "/^ Yellow/"}) or Db.stu.find ({name:{$regex: "^ Yellow"}})

3.5 Custom (function) query $where
MongoDB's terminal is actually also JS compiler, using JS anonymous function
Db.stu.find ({
$where: JS anonymous function {
//must return a value of type bool is a query condition
return Condition
}
})

For example: query for students older than 30
Db.stu.find ({
$where: Function () {
return this.age>30;
}
})

3.6 Limit and Skip:
db. Collection. Find (). Limit (num): Displays only the first num bars of the query results
db. Collection. Find (). Skip (num): The previous NUM bar data is displayed from the next bar

can be used together:
db.stu.find ({}). Skip (5). Limit (3)
//Over the first 5 lines starting from 6th show 3
db.stu.find ({}). Limit (3). Skip (5)
//skip and limit pick order execution effect is the same

3.7 Projection (specifies that the field displays query results):
db. Collection. Find ({Condition},{field 1:1, Field 2:1, Field 3:0})
//condition followed by a parameter, 0 means the display is not displayed in the query Results 1 represents

For example: View only name and gender:
Db.stu.find ({},{name:1, gender:1})
//_id is displayed by default, if it is not displayed _id need special designation
//projection set to 1 except _id other parameters are displayed by default

do not show _id:
db.stu.find ({},{_id:0,name:1})

3.8 Sorts sort ():
db. Collection. Find (). sort ({field 1:1, field 2:-1})
//Specify field sort, 1 for ascending, 1 for descending

For example: Sort by age ascending, sex descending
db.stu.find ({}). sort ({age:1,gender:-1})

3.9 Statistics Number count ():
db. Collection. Find ({condition}). Count ()
or DB. Collection. Count ({condition})

For example: Statistics on the number of boys
db.stu.find ({gender:1}). Count ()
or Db.stu.count ({gender:1})

For example: Boys with a statistical age greater than 18
Db.stu.count ({age:{&gt:18}},gender:1)

3.10 de-duplication distinct ():
db. Collection. Distinct ("field", {condition})

For example: Find out which provinces a boy older than 18 is from
db.stu.distinct ("Hometown", {age:{&gt:18},gender:1})





Linux under the terminal command of MongoDB set up, insert, delete, modify, query

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.