#MongoDB中有三元素:数据库,集合,文档,其中“集合”就是对应关系数据库中的“表”,“文档”对应“行”。

#创建数据库testdb数据库,使用以下语句
mongos> use testdb;
#查询数据库,要显示数据库必须插入至少一条文档
mongos> show dbs;
#插入数据文档
mongos> db.tablename.insert({"name":"antian"});
#数据库生成了
mongos> show dbs;
testdb  0.078GB

#删除数据库
#查询数据库
mongos> show dbs;
testdb  0.078GB
#进入数据库
mongos> use testdb;
#删除数据库
mongos> db.dropDatabase();
{ "dropped" : "testdb", "ok" : 1 }
#查询数据库
mongos> show dbs;

#MongoDB数据类型
MongoDB支持许多数据类型的列表下面给出:
String : 这是最常用的数据类型来存储数据。在MongoDB中的字符串必须是有效的UTF-8。
Integer : 这种类型是用来存储一个数值。整数可以是32位或64位,这取决于您的服务器。
Boolean : 此类型用于存储一个布尔值 (true/ false) 。
Double : 这种类型是用来存储浮点值。
Min/ Max keys : 这种类型被用来对BSON元素的最低和最高值比较。
Arrays : 使用此类型的数组或列表或多个值存储到一个键。
Timestamp : 时间戳。这可以方便记录时的文件已被修改或添加。
Object : 此数据类型用于嵌入式的文件。
Null : 这种类型是用来存储一个Null值。
Symbol : 此数据类型用于字符串相同,但它通常是保留给特定符号类型的语言使用。
Date : 此数据类型用于存储当前日期或时间的UNIX时间格式。可以指定自己的日期和时间,日期和年,月,日到创建对象。
Object ID : 此数据类型用于存储文档的ID。
Binary data : 此数据类型用于存储二进制数据。
Code : 此数据类型用于存储到文档中的JavaScript代码。
Regular expression : 此数据类型用于存储正则表

#创建集合
#进入数据库
mongos> use testdb;
#创建集合
mongos> db.createCollection("mycollection")
mongos> show tables;
mycollection

#删除集合
#进入数据库
mongos> use testdb;
mongos> show tables;
mycollection
mongos> db.mycollection.drop();
true
mongos> show tables;

#插入文档
#插入一条文档
mongos> db.tablesname.insert([{"name":"aaaaa","age":"18"}
#插入两条文档
mongos> db.tablesname.insert([{"name":"ddddd","age":"18"},{"name":"eeee","age":"10"}]);
#格式化查询文档
mongos> db.tablename.find().pretty();
#查询一个文档:
mongos> db.tablesname.findOne();

#更新文档
#显示集合文档
mongos> db.v.find();
{ "_id" : ObjectId("55113e5477eaee1608881c84"), "name" : "antian" }
#更新文档
mongos> db.tablename.update({"name":"antian"},{"name":"wuhan"});
#显示集合文档
mongos> db.tablename.find();
{ "_id" : ObjectId("55113e5477eaee1608881c84"), "name" : "wuhan" }

#删除文档
#删除文档内容
mongos> db.tablename.remove({"name":"wuhan"});
#删除文档:db.tablename.drop();

#投影
db.tablename.find({},{"sip":1,_id:1});

#限制记录
mongos> db.tablename.find({},{"sip":1,_id:0}).limit(2);

#排序文档
#降序
mongos> db.tablename.find({},{"age":1,_id:0}).sort({"age":-1});
#升序
mongos> db.tablename.find({},{"age":1,_id:0}).sort({"age":1});

#创建索引
mongos> db.tablename.ensureIndex({"id":1})


#mongos> db.tablesname.stats();			#数据库集合解释
{
	"sharded" : false,					#分片
	"primary" : "shard0001",
	"ns" : "6xx.testdocument01",		#集合命令
	"count" : 2100,						#集合文档总数
	"size" : 504000,					#集合空间大小,单位为字节
	"avgObjSize" : 240,					#平均对象占用的空间
	"numExtents" : 4,					#连续分配的数据库
	"storageSize" : 696320,				#给整个集合分配的空间,当删除集合文档时,这个值不会降低
	"lastExtentSize" : 524288,			#最近分配的块的大小
	"paddingFactor" : 1,				#
	"paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0. It remains hard coded to 1.0 for compatibility only.",
	"userFlags" : 1,
	"capped" : false,
	"nindexes" : 1,
	"totalIndexSize" : 81760,			#所有索引大小的总和
	"indexSizes" : {					#列出集合的所有索引字段,以及索引大小
		"_id_" : 81760
	},
	"ok" : 1
}
--------------------------------------------------------------------
MongoDB命令管理
--------------------------------------------------------------------

shell操作数据库


一、超级用户相关:

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

10. #查看主从复制状态

    db.printReplicationInfo()

11. #修复数据库

    db.repairDatabase()

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

    db.setProfilingLevel(1)

13. #查看profiling

    show profile

14. #拷贝数据库

    db.copyDatabase('mail_addr','mail_addr_tmp')

15. #删除collection

    db.mail_addr.drop()

16. #删除当前的数据库

    db.dropDatabase()



二、增删改

1. #存储嵌套的对象

   db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})

2. #存储数组对象

   db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})

3. #根据query条件修改,如果不存在则插入,允许修改多条记录

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

4. #删除yy=5的记录

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

5. #删除所有的记录

   db.foo.remove()

 

三、索引

1. #增加索引:1(ascending),-1(descending)

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

2. #索引子对象

   db.user_addr.ensureIndex({'Al.Em': 1})

3. #查看索引信息

   db.foo.getIndexes()

   db.foo.getIndexKeys()

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

   db.user_addr.dropIndex('Al.Em_1')

 

四、查询

1. #查找所有

   db.foo.find()

2. #查找一条记录

   db.foo.findOne()

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

   db.foo.find({'msg':'Hello 1'}).limit(10)

4. #sort排序

   db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1})
   db.deliver_status.find().sort({'Ct':-1}).limit(1)

5. #count操作

   db.user_addr.count()

6. #distinct操作,查询指定列,去重复

   db.foo.distinct('msg')

7. #”>=”操作

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

8. #子对象的查找

   db.foo.find({'address.city':'beijing'})



五、管理

1. #查看collection数据的大小

   db.deliver_status.dataSize()

2. #查看colleciont状态

   db.deliver_status.stats()

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

   db.deliver_status.totalIndexSize()

 

六、advanced queries:高级查询

条件操作符 
$gt : > 
$lt : < 
$gte: >= 
$lte: <= 
$ne : !=、<> 
$in : in 
$nin: not in 
$all: all 
$not: 反匹配(1.3.3及以上版本) 

查询 name <> "bruce" and age >= 18 的数据 
db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}}); 

查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 
db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)}); 

查询 age in (20,22,24,26) 的数据 
db.users.find({age: {$in: [20,22,24,26]}}); 

查询 age取模10等于0 的数据 
db.users.find('this.age % 10 == 0'); 
或者 
db.users.find({age : {$mod : [10, 0]}}); 

匹配所有 
db.users.find({favorite_number : {$all : [6, 8]}}); 
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } 

查询不匹配name=B*带头的记录 
db.users.find({name: {$not: /^B.*/}}); 
查询 age取模10不等于0 的数据 
db.users.find({age : {$not: {$mod : [10, 0]}}}); 

#返回部分字段 
选择返回age和_id字段(_id字段总是会被返回) 
db.users.find({}, {age:1}); 
db.users.find({}, {age:3}); 
db.users.find({}, {age:true}); 
db.users.find({ name : "bruce" }, {age:1}); 
0为false, 非0为true 

选择返回age、address和_id字段 
db.users.find({ name : "bruce" }, {age:1, address:1}); 

排除返回age、address和_id字段 
db.users.find({}, {age:0, address:false}); 
db.users.find({ name : "bruce" }, {age:0, address:false}); 

数组元素个数判断 
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 
匹配db.users.find({favorite_number: {$size: 3}}); 
不匹配db.users.find({favorite_number: {$size: 2}}); 

$exists判断字段是否存在 
查询所有存在name字段的记录 
db.users.find({name: {$exists: true}}); 
查询所有不存在phone字段的记录 
db.users.find({phone: {$exists: false}}); 

$type判断字段类型 
查询所有name字段是字符类型的 
db.users.find({name: {$type: 2}}); 
查询所有age字段是整型的 
db.users.find({age: {$type: 16}}); 

对于字符字段,可以使用正则表达式 
查询以字母b或者B带头的所有记录 
db.users.find({name: /^b.*/i}); 

$elemMatch(1.3.1及以上版本) 
为数组的字段中匹配其中某个元素 

Javascript查询和$where查询 
查询 age > 18 的记录,以下查询都一样 
db.users.find({age: {$gt: 18}}); 
db.users.find({$where: "this.age > 18"}); 
db.users.find("this.age > 18"); 
f = function() {return this.age > 18} db.users.find(f); 

排序sort() 
以年龄升序asc 
db.users.find().sort({age: 1}); 
以年龄降序desc 
db.users.find().sort({age: -1}); 

限制返回记录数量limit() 
返回5条记录 
db.users.find().limit(5); 
返回3条记录并打印信息 
db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); 
结果 
my age is 18 
my age is 19 
my age is 20 

限制返回记录的开始点skip() 
从第3条记录开始,返回5条记录(limit 3, 5) 
db.users.find().skip(3).limit(5); 

查询记录条数count() 
db.users.find().count(); 
db.users.find({age:18}).count(); 
以下返回的不是5,而是user表中所有的记录数量 
db.users.find().skip(10).limit(5).count(); 
如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 
db.users.find().skip(10).limit(5).count(true); 

分组group() 
假设test表只有以下一条数据 
{ domain: "www.mongodb.org" 
, invoked_at: {d:"2009-11-03", t:"17:14:05"} 
, response_time: 0.05 
, http_action: "GET /display/DOCS/Aggregation" 
} 
使用group统计test表11月份的数据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 
} 
] 

 

Java 应用示例 

要使用Java操作MongoDB的话,要到官方网站下载一个驱动包,把包导入后,可以尝试来操作了(记得一定要开着服务器) 

首先介绍一下比较常用的几个类 

Mongo:连接服务器,执行一些数据库操作的选项,如新建立一个数据库等 

DB:对应一个数据库,可以用来建立集合等操作 

DBCollection:对应一个集合(类似表),可能是我们用得最多的,可以添加删除记录等 

DBObjec:接口和BasicDBObject对象:表示一个具体的记录,BasicDBObject实现了DBObject,因为是key-value的数据结构,所以用起来其实和HashMap是基本一致的 

DBCursor:用来遍历取得的数据,实现了Iterable和Iterator 

接下来实际的操作一下,代码如下: 

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"); 

//获得数据库服务

Mongo m = new Mongo("localhost", 27017); 

//得到数据库mytest

DB db = m.getDB("mytest"); 

//得到mytest数据库下所有表名

    Set<String> colls = db.getCollectionNames(); 

    for (String s : colls) { 

System.out.println(s); 

} 

//得到testCollection表

DBCollection coll = db.getCollection("testCollection"); 

//new 一个BasicDBObject对象doc

BasicDBObject doc = new BasicDBObject(); 

//赋值

    doc.put("name", "MongoDB"); 

    doc.put("type", "database"); 

doc.put("count", 1); 

//又new 一个BasicDBObject对象info

    BasicDBObject info = new BasicDBObject(); 

    info.put("x", 203); 

info.put("y", 102); 

//把info放入doc

doc.put("info", info); 

//向testCollection表中插入一条数据

coll.insert(doc); 

//查询一条数据

    DBObject myDoc = coll.findOne(); 

    System.out.println(myDoc); 

    

    //循环插入100条数据到testCollection

    for (int i=0; i < 100; 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(); 

    while(cur.hasNext()) {

-----------------------------------------------------
DB methods:
        db.addUser(username, password[, readOnly=false])
        db.auth(username, password)
        db.cloneDatabase(fromhost)
        db.commandHelp(name) returns the help for the command
        db.copyDatabase(fromdb, todb, fromhost)
        db.createCollection(name, { size : ..., capped : ..., max : ... } )
        db.currentOp() displays the current operation in the db
        db.dropDatabase()
        db.eval(func, args) run code server-side
        db.getCollection(cname) same as db['cname'] or db.cname
        db.getCollectionNames()
        db.getLastError() - just returns the err msg string
        db.getLastErrorObj() - return full status object
        db.getMongo() get the server connection object
        db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
        db.getName()
        db.getPrevError()
        db.getProfilingLevel() - deprecated
        db.getProfilingStatus() - returns if profiling is on and slow threshold

        db.getReplicationInfo()
        db.getSiblingDB(name) get the db at the same server as this one
        db.isMaster() check replica primary status
        db.killOp(opid) kills the current operation in the db
        db.listCommands() lists all the db commands
        db.logout()
        db.printCollectionStats()
        db.printReplicationInfo()
        db.printSlaveReplicationInfo()
        db.printShardingStatus()
        db.removeUser(username)
        db.repairDatabase()
        db.resetError()
        db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
        db.serverStatus()
        db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
        db.shutdownServer()
        db.stats()
        db.version() current version of the server
        db.getMongo().setSlaveOk() allow queries on a replication slave server
        db.fsyncLock() flush data to disk and lock server for backups
        db.fsyncUnock() unlocks server following a db.fsyncLock()
>