MongoDB is written in C + +, whose name comes from the middle part of the word humongous, and its ambition is the processing of massive data from its name. One of the most concise descriptions of it is: scalable, high-performance, open source, Schema-free, document-oriented database. The main goal of MongoDB is to set up a bridge between key/value storage (which provides high performance and high scalability) as well as traditional RDBMS systems (rich functionality), combining the advantages of both.
Installation and use:
First, you install MongoDB on Ubuntu.
Download MongoDB, now the latest production version 1.7.0
1. Unzip the file.
$ TAR-XVF mongodb-linux-i686-1.4.3.tgz
2. Create a data directory for MongoDB, by default it stores the data in the/data/db
$ sudo mkdir-p/data/db/
$ sudo chown ' id-u '/data/db
3. Start the MongoDB service.
$ CD Mongodb-linux-i686-1.4.3/bin
$./mongod
4. Open another terminal and make sure you are in the bin directory of MongoDB and enter the following command.
$./mongo
Some concepts
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:notinall: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:newDate(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: [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 determines whether a field exists to query 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 Judgment field type query all name fields are 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 query for the records of age > 18, the following queries are all the same db.users.find ({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: "one-to-one",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
}
]
Java Application Example
To use the Java Operation MongoDB, to the official website to download a driver package, the package after the import, you can try to operate (remember to open the server)
Let's start by introducing some of the more commonly used classes
Mongo: Connect to the server, perform some database operation options, such as creating a new database, etc.
DB: Corresponds to a database that can be used to set up operations such as collections
Dbcollection: Corresponding to a set (similar to a table), it may be that we use the most, you can add delete records, etc.
Dbobjec: Interface and Basicdbobject object: Represents a specific record, Basicdbobject implements DBObject, because it is the data structure of key-value, so it is basically consistent with HashMap
Dbcursor: Used to traverse the obtained data, realizing the iterable and iterator
Then the actual operation, the code is as follows:
Import java.net.UnknownHostException;
Import java.util.List;
Import Java.util.Set;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;
Import Com.mongodb.Mongo;
Import com.mongodb.MongoException;
public class Mongodbtest {
public static void Main (string[] args) throws Unknownhostexception, Mongoexception {
Mongo m = new Mongo ();
Mongo m = new Mongo ("localhost");
Get database service
Mongo m = new Mongo ("localhost", 27017);
Get Database MyTest
DB db = M.getdb ("mytest");
Get all the table names under the MyTest database
Set<string> colls = Db.getcollectionnames ();
for (String s:colls) {
System.out.println (s);
}
Get testcollection Table
Dbcollection coll = db.getcollection ("testcollection");
New A Basicdbobject object doc
Basicdbobject doc = new Basicdbobject ();
Assign value
Doc.put ("name", "MongoDB");
Doc.put ("type", "database");
Doc.put ("Count", 1);
Another new one Basicdbobject object info
Basicdbobject info = new Basicdbobject ();
Info.put ("x", 203);
Info.put ("Y", 102);
Put info into doc
Doc.put ("info", info);
Insert a piece of data into the Testcollection table
Coll.insert (DOC);
Querying a single piece of data
DBObject MyDoc = Coll.findone ();
System.out.println (MYDOC);
Loop Insert 100 data to Testcollection
for (int i=0; i <; i++) {
Coll.insert (New Basicdbobject (). Append ("I", I));
}
Counting Documents in A Collection
System.out.println (Coll.getcount ());
Using a Cursor to Get all the Documents
Dbcursor cur = coll.find ();
MongoDB Common Commands