MongoDB basic operations

Basic operation

  • MongoDB stores data as a document, and the data structure consists of key-value (key=>value) pairs
  • MongoDB documents are similar to JSON objects, and field values ​​can contain other documents, arrays, arrays of documents
  • Install and manage the mongodb environment
  • Complete database and collection management
  • Data addition, modification, deletion, query

noun

SQL terms/concepts MongoDB terms/concepts explain
database database database
table collection Database table/collection
row document Data record line/document
column field data field/domain
index index index
table joins   Table joins, MongoDB does not support
primary key primary key Primary key, MongoDB automatically sets the _id field as the primary key
  • Three elements: database, collection, document
    • A collection is a table in a relational database
    • Documents correspond to rows in a relational database
  • A document is an object composed of key-value pairs, which is an extended Bson form of json
{'name':'guojing','gender':'男'}
  • Collection: Similar to a table in a relational database, it stores multiple documents, and the structure is not fixed. For example, the following documents can be stored in a collection
{'name':'guojing','gender':'男'}
{'name':'huangrong','age':18}
{'book':'shuihuzhuan','heros':'108'}
  • Database: is a physical container for a collection, a database can contain multiple documents
  • A server usually has multiple databases

Install

  • Download the version of mongodb, two points
    • According to industry rules, the even number is the stable version, such as 1.6.X, and the odd number is the development version, such as 1.7.X
    • 32bit mongodb can only store up to 2G of data, 64bit has no limit
  • Go to the official website and select the appropriate version to download
  • decompress
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
  • Add the executable to the PATH path
export PATH=/usr/local/mongodb/bin:$PATH

manage mongo

  • The configuration file is 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 a js compiler.
mongo
  • Order
db查看当前数据库名称
db.stats()查看当前数据库信息
  • Terminal exits connection
exit
或ctrl+c
  • GUI: robomongo, find the running program in the bin directory after decompression
  • The interface is as follows:

gui

database switch

  • View the current database name
db
  • View all database names
  • List all databases that exist physically
show dbs
  • switch database
  • If the database does not exist, point to the database, but not create it, the database is not created until data is inserted or the collection is created
use 数据库名称
  • The default database is test, if you do not create a new database, the collection will be stored in the test database

database delete

  • delete the currently pointed database
  • Do nothing if the database does not exist
db.dropDatabase()


Collection creation

  • grammar
db.createCollection(name, options)
  • name is the name of the collection to create
  • options is a document that specifies the configuration of the collection
  • The options parameter is optional, so only need to specify the collection name. The following is a list of options that can be used:
  • Example 1: Unlimited collection size
db.createCollection("stu")
  • Example 2: Limit the size of the set, and you can view the effect after learning to insert a statement
  • Parameter capped: The default value is false, which means no upper limit is set, and the value is true, which means setting the upper limit.
  • Parameter size: When the capped value is true, this parameter needs to be specified, indicating the upper limit size. When the document reaches the upper limit, the previous data will be overwritten, in bytes
db.createCollection("sub", { capped : true, size : 10 } )

View a collection of the current database

  • grammar
show collections

delete

  • grammar
db.集合名称.drop()

type of data

  • The following table shows several data types commonly used in MongoDB:
  • Object ID: Document ID
  • String: String, most commonly used, must be valid UTF-8
  • Boolean: stores a boolean value, true or false
  • Integer: Integer can be 32-bit or 64-bit, depending on the server
  • Double: store floating point value
  • Arrays: Arrays or lists, where multiple values ​​are stored into one key
  • Object: for embedded documents, i.e. one value for one document
  • Null: store Null value
  • Timestamp: Timestamp
  • Date: UNIX time format to store 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 each document with a unique _id 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's service process id in the next 2 bytes

The last 3 bytes are simple increment values

insert

  • grammar
db.集合名称.insert(document)
  • 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)

Simple query

  • grammar
db.集合名称.find()

renew

  • grammar
db.集合名称.update(
   <query>,
   <update>,
   {multi: <boolean>}
)
  • Parameter query: query condition, similar to the where part in the sql statement update
  • Parameter update: update operator, similar to the set part of the sql statement update
  • Parameter multi: optional, the 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 3: Full document update
db.stu.update({name:'hr'},{name:'mnc'})
  • Example 4: Specify attribute update, through operator $set
db.stu.insert({name:'hr',gender:0})
db.stu.update({name:'hr'},{$set:{name:'hys'}})
  • Example 5: Modify multiple matched data
db.stu.update({},{$set:{gender:0}},{multi:true})

keep

  • grammar
db.集合名称.save(document)
  • Modify 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.集合名称.remove(
   <query>,
   {
     justOne: <boolean>
   }
)
  • Parameter query: optional, the condition of the deleted document
  • Parameter justOne: optional, if set to true or 1, only one item will be deleted, the default is false, which means that multiple items will be deleted
  • Example 8: delete only the first match
db.stu.remove({gender:0},{justOne:true})
  • Example 9: Delete all
db.stu.remove({})

example about size

  • Example 10
  • Create a collection
db.createCollection('sub',{capped:true,size:10})
  • Insert the 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()
  • Insert the third database query
db.sub.insert({title:'sql',count:8})
db.sub.find()
  • Insert the fourth database query
db.sub.insert({title:'django',count:12})
db.sub.find()
  • Insert the fifth database query
db.sub.insert({title:'python',count:14})
db.sub.find()


data query

Basic query

  • Method find(): query
db.集合名称.find({条件文档})
  • Method findOne(): query, only return the first one
db.集合名称.findOne({条件文档})
  • Method pretty(): format the result
db.集合名称.find({条件文档}).pretty()

comparison operator

  • Equal, 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 whose name is equal to 'gj'
db.stu.find({name:'gj'})
  • Example 2: Query students whose age is greater than or equal to 18
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 default is a logical AND relationship
  • 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})
  • Logical OR: use $or
  • Example 4: Query students whose age is greater than 18, or whose gender is 0
db.stu.find({$or:[{age:{$gt:18}},{gender:1}]})
  • and is used with or
  • 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 whether it is within a certain range
  • Example 6: Query students whose ages are 18 and 28
db.stu.find({age:{$in:[18,28]}})

Support regular expressions

  • Write regular expressions using // or $regex
  • Example 7: Query students with the surname Huang
db.stu.find({name:/^黄/})
db.stu.find({name:{$regex:'^黄'}}})

custom query

  • Write a function after $where to return the data that meets the conditions
  • Example 7: Query students whose age is greater than 30
db.stu.find({$where:function(){return this.age>20}})


Limit

  • Method limit(): used to read a specified number of documents
  • grammar:
db.集合名称.find().limit(NUMBER)
  • The parameter NUMBER indicates the number of documents to be obtained
  • If no arguments are specified, display all documents in the collection
  • Example 1: Query 2 pieces of student information
db.stu.find().limit(2)

skip

  • Method skip(): used to skip a specified number of documents
  • grammar:
db.集合名称.find().skip(NUMBER)
  • The parameter NUMBER indicates the number of skipped records, the default value is 0
  • Example 2: Query student information starting from item 3
db.stu.find().skip(2)

use together

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

  • Create a dataset

for(i=0;i<15;i++){db.t1.insert({_id:i})}
  • Querying data from 5 to 8
db.stu.find().limit(4).skip(5)
db.stu.find().skip(5).limit(4)


projection

  • In the returned results of the query, only the necessary fields are selected, rather than the entire field of a document
  • For example: a document has 5 fields, only 3 need to be displayed, and 3 of them can be projected
  • grammar:
  • The parameter is a field and a value, a value of 1 means display, and a value of 0 does not display
db.集合名称.find({},{字段名称:1,...})
  • For the fields that need to be displayed, set it to 1, otherwise it will not be displayed
  • Special: For the _id column, it is displayed by default. If it is not displayed, it needs to 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})

sort

  • The method sort() is used to sort the result set
  • grammar
db.集合名称.find().sort({字段:1,...})
  • Parameter 1 is in ascending order
  • Parameter -1 is for descending order
  • Example 1: Descending by gender, then ascending by age
db.stu.find().sort({gender:-1,age:1})

Statistics

  • The method count() is used to count the number of documents in the result set
  • grammar
db.集合名称.find({条件}).count()
  • can also be used with
db.集合名称.count({条件})
  • Example 1: Counting the number of boys
db.stu.find({gender:1}).count()
  • Example 2: Count the number of boys over the age of 20
db.stu.count({age:{$gt:20},gender:1})


Eliminate duplicates

  • The method distinct() deduplicates the data
  • grammar
db.集合名称.distinct('去重字段',{条件})
  • Example 1: Find genders whose age is greater than 18 (de-duplication)
db.stu.distinct('gender',{age:{$gt:18}})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325182786&siteId=291194637