MONGO Database Base Operations

Source: Internet
Author: User

Concept

A Mongod service can have multiple databases, each database can have multiple tables, where the table is called collection, each collection can hold multiple documents (document), each document is Bson (binary JSON) in the form of a hard disk, so you can store more complex data types. It is stored in a single document, and you can add or delete fields to one or a batch of documents without affecting other documents, which is the so-called Schema-free, which is also the main advantage of the document-type database. Unlike the general Key-value database, it stores structure information in value, so you can read, write, and count some domains like a relational database. MONGO's biggest feature is that the query language he supports is very powerful, and its syntax is a bit like an object-oriented query language that almost implements most of the functionality of a relational database single-table query, and also supports indexing of data. MONGO can also solve the query efficiency of massive data, according to official documents, when the amount of data reached more than 50GB data, MONGO database access speed is more than MySQL10 times.

BSON

Bson is the abbreviation for binary JSON and is a binary encoded format for JSON document objects. Bson supports inserting document objects and arrays into other document objects and arrays as well as JSON, extending the JSON data type. For example: Bson has a date type and a bindate type.

Bson is likened to a binary interchange format, like protocol buffers, but Bson is more "schema-less" than it is, with very good flexibility but with a slightly larger footprint.

Bson has the following three features:

1. Lightweight

2. Cross-platform

3. High efficiency

Name space

MongoDB stores Bson objects to collections, a series of database names and collection names called a namespace. As: java.util.List; used to manage data in a database.

Index

MongoDB can index a field, create a composite index, a unique index, or delete an index, which means more space overhead. By default, each table will have a unique index: _id, if you insert data without specifying _ID, the service automatically generates a _id, in order to make full use of the existing indexes and reduce the space cost, it is best to specify a unique key for the _id, usually with the object's ID is more appropriate, such as the ID of the product.



Shell Operations Database:



1. Super User-Related:

1. #进入数据库admin

Use admin

2. #增加或修改用户密码

Db.adduser (' name ', ' pwd ')

3. #查看用户列表

Db.system.users.find ()

4. #用户认证

Db.auth (' name ', ' pwd ')

5. #删除用户

Db.removeuser (' name ')

6. #查看所有用户

Show Users

7. #查看所有数据库

Show DBS

8. #查看所有的collection

Show collections

9. #查看各collection的状态

Db.printcollectionstats ()

Ten. #查看主从复制状态

Db.printreplicationinfo ()

#修复数据库.

Db.repairdatabase ()

#设置记录profiling, 0=off 1=slow 2=all

Db.setprofilinglevel (1)

#查看profiling.

Show profile

#拷贝数据库

Db.copydatabase (' mail_addr ', ' mail_addr_tmp ')

#删除collection.

Db.mail_addr.drop ()

#删除当前的数据库

Db.dropdatabase ()



2. Adding and deleting changes

1. #存储嵌套的对象

Db.foo.save ({' name ': ' Ysz ', ' address ': {' city ': ' Beijing ', ' Post ': 100096}, ' phone ': [138,139]})



2. #存储数组对象

Db.user_addr.save ({' Uid ': ' [email protected] ', ' Al ': [' [email protected] ', ' [email protected] ']})



3. #根据query条件修改, insert if not present, allow multiple records to be modified

Db.foo.update ({' yy ': 5},{' $set ': {' xx ': 2}},upsert=true,multi=true)

4. Records of #删除yy =5

Db.foo.remove ({' yy ': 5})

5. #删除所有的记录

Db.foo.remove ()



3. Index

1. #增加索引: 1 (Ascending), -1 (Descending)

2. Db.foo.ensureIndex ({firstname:1, lastname:1}, {unique:true});

3. #索引子对象

4. Db.user_addr.ensureIndex ({' Al.em ': 1})

5. #查看索引信息

6. Db.foo.getIndexes ()

7. Db.foo.getIndexKeys ()

8. #根据索引名删除索引

9. Db.user_addr.dropIndex (' al.em_1 ')



4. Enquiry

1. #查找所有

2. Db.foo.find ()

3. #查找一条记录

4. Db.foo.findOne ()

5. #根据条件检索10条记录

6. Db.foo.find ({' msg ': ' Hello 1 '}). Limit (10)

7. #sort排序

8. Db.deliver_status.find ({' From ': ' [email protected] '}). Sort ({' Dt ',-1})

9. Db.deliver_status.find (). Sort ({' Ct ': -1}). Limit (1)

Ten. #count操作

Db.user_addr.count ()

#distinct操作, query the specified column to repeat

Db.foo.distinct (' msg ')

# ">=" action

Db.foo.find ({"timestamp": {"$gte": 2}})

#子对象的查找

Db.foo.find ({' address.city ': ' Beijing ')

5. Management

1. #查看collection数据的大小

2. Db.deliver_status.dataSize ()

3. #查看colleciont状态

4. Db.deliver_status.stats ()

5. #查询所有索引的大小

6. Db.deliver_status.totalIndexSize ()



5. Advanced Queries: Senior Enquiry


Conditional operator
$GT: >
$LT: <
$gte: >=
$lte: <=
$ne:! =, <>
$in: In
$nin: Not in
$all: All
$not: Anti-match (1.3.3 and later)

Query name <> "Bruce" and age >= 18 data
Db.users.find ({name: {$ne: "Bruce"}, Age: {$gte: 18}});

Query creation_date > ' 2010-01-01 ' and creation_date <= ' 2010-12-31 ' data
Db.users.find ({creation_date:{$gt: new Date (2010,0,1), $lte: new Date (2010,11,31)});

Querying for data in the age (20,22,24,26)
Db.users.find ({age: {$in: [20,22,24,26]}});

Query age modulo 10 equals 0 of data
Db.users.find (' this.age% 10 = = 0 ');
Or
Db.users.find ({age: {$mod: [10, 0]}});

Match all
Db.users.find ({favorite_number: {$all: [6, 8]}});
Can query out {name: ' David ', age:26, Favorite_number: [6, 8, 9]}
Can not query out {name: ' David ', age:26, Favorite_number: [6, 7, 9]}

Query mismatch name=b* lead record
Db.users.find ({name: {$not:/^b.*/}});
Query age modulo 10 is not equal to 0 data
Db.users.find ({age: {$not: {$mod: [10, 0]}}});

#返回部分字段
Choose to return the Age and _id fields (the _id field will always be returned)
Db.users.find ({}, {age:1});
Db.users.find ({}, {age:3});
Db.users.find ({}, {age:true});
Db.users.find ({name: "Bruce"}, {age:1});
0 is false, not 0 is true

Choose to return the age, address, and _id fields
Db.users.find ({name: "Bruce"}, {age:1, address:1});

Exclude return age, address, and _id fields
Db.users.find ({}, {age:0, address:false});
Db.users.find ({name: "Bruce"}, {age:0, address:false});

Number of array elements
For {name: ' David ', age:26, Favorite_number: [6, 7, 9]} record
Match Db.users.find ({favorite_number: {$size: 3}});
Mismatch Db.users.find ({favorite_number: {$size: 2}});

$exists determine if a field exists
Querying all records that exist in the name field
Db.users.find ({name: {$exists: true}});
Query all records that do not exist in the phone field
Db.users.find ({phone: {$exists: false}});

$type Judging field types
Query all name fields are of character type
Db.users.find ({name: {$type: 2}});
Query all age fields are integral type
Db.users.find ({age: {$type: 16}});

For character fields, you can use regular expressions
Query all records that lead with the letter B or B
Db.users.find ({name:/^b.*/i});

$elemMatch (1.3.1 and above)
Match one of these elements in an array field

JavaScript queries and $where queries
Check the records for age > 18 and the following queries are all the same
Db.users.find ({age: {$gt: 18}});
Db.users.find ({$where: "This.age > 18"});
Db.users.find ("This.age > 18");
f = function () {return this.age > Db.users.find} (f);

Sorting sort ()
With age ascending ASC
Db.users.find (). Sort ({age:1});
Descending desc by age
Db.users.find (). Sort ({Age:-1});

Limit the number of records returned ()
Returns 5 Records
Db.users.find (). Limit (5);
Return 3 records and print information
Db.users.find (). Limit (3). ForEach (user) {print (' my age is ' + user.age)});
Results
My age is 18
My age is 19
My age is 20

Limit the start point of the return record Skip ()
Starting from 3rd record, return 5 records (limit 3, 5)
Db.users.find (). Skip (3). Limit (5);

Number of query record bars count ()
Db.users.find (). Count ();
Db.users.find ({age:18}). Count ();
The following return is not 5, but the number of records in the user table
Db.users.find (). Skip (. Limit (5). Count ();
If you want to return the number of records after the limit, use count (true) or count (not 0)
Db.users.find (). Skip (. Limit (5). Count (True);

Grouping group ()
Suppose the test table has only one of the following data
{domain: "www.mongodb.org"
, Invoked_at: {d: "2009-11-03", T: "17:14:05"}
, response_time:0.05
, http_action: "Get/display/docs/aggregation"
}
Use the Group Statistics test table November Data count:count (*), Total_time:sum (Response_time), Avg_time:total_time/count;
Db.test.group (
{cond: {"INVOKED_AT.D": {$gt: "2009-11", $lt: "2009-12"}}
, key: {http_action:true}
, initial: {count:0, total_time:0}
, Reduce:function (Doc, out) {out.count++; Out.total_time+=doc.response_time}
, Finalize:function (out) {out.avg_time = Out.total_time/out.count}
} );

[
{
"Http_action": "Get/display/docs/aggregation",
"Count": 1,
"Total_time": 0.05,
"Avg_time": 0.05
}
]



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.