admin 管理员组

文章数量: 1184232


2023年12月19日发(作者:lovephp是什么意思)

MongoDB数据库简单介绍(一)

Mongo是一个高性能,开源,无模式的文档型数据库,它在许多场景下可用于替代传统的关系型数据库或键/值存储方式。Mongo使用C++开发, 提供了以下功能:

1. 面向集合的存储:适合存储对象及JSON形式的数据。

2. 动态查询:Mongo支持丰富的查询表达式。查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。

3. 完整的索引支持:包括文档内嵌对象及数组。Mongo的查询优化器会分析查询表达式,并生成一个高效的查询计划。

4. 查询监视:Mongo包含一个监视工具用于分析数据库操作的性能。

5. 复制及自动故障转移:Mongo数据库支持服务器之间的数据复制,支持主-从模式及服务器之间的相互复制。复制的主要目标是提供冗余及自 动故障转移。

6. 高效的传统存储方式:支持二进制数据及大型对象(如照片或图片)。

7. 自动分片以支持云级别的伸缩性(处于早期alpha阶段):自动分片功能支持水平的数据库集群,可动态添加额外的机器。

MongoDB的主要目标是在键/值存储方式(提供了高性能和高度伸缩性)以及传统的RDBMS系统(丰富的功能)架起一座桥梁,集两者的优势于一 身。根据官方网站的描述,Mongo 适合用于以下场景:

1. 网站数据:Mongo非常适合实时的插入,更新与查询,并具备网站实时数据存储所需的复制及高度伸缩性。

2. 缓存:由于性能很高,Mongo也适合作为信息基础设施的缓存层。在系统重启之后,由Mongo搭建的持久化缓存层可以避免下层的数据源 过载。

3. 大尺寸,低价值的数据:使用传统的关系型数据库存储一些数据时可能会比较昂贵,在此之前,很多时候程序员往往会选择传统的文件进行存储。

4. 高伸缩性的场景:Mongo非常适合由数十或数百台服务器组成的数据库。Mongo的路线图中已经包含对MapReduce引擎的内置支 持。

5. 用于对象及JSON数据的存储:Mongo的BSON数据格式非常适合文档化格式的存储

及查询。

自然,MongoDB的使用也会有一些限制,例如它不适合:

1. 高度事务性的系统:例如银行或会计系统。传统的关系型数据库目前还是更适用于需要大量原子性复杂事务的应用程序。

2. 传统的商业智能应用:针对特定问题的BI数据库会对产生高度优化的查询方式。对于此类应用,数据仓库可能是更合适的选择。

3. 需要SQL的问题

MongoDB支持OS X、Linux及Windows等操作系统,并提供了Python,PHP,Ruby,Java,C,C#,Javascript,Perl及C++语言的驱动程序,社区中也提供了对Erlang 及.NET等平台的驱动程序

MongoDB下载:

/display/DOCS/Downloads

/lin ...

MongoDB安装:

[falcon@ ~/mongodb]$tar xvzf

[falcon@ ~/mongodb]$mv mongodb-linux-i686-v1.2-latest mongodb

[falcon@ ~/mongodb]$cd mongodb

[falcon@ ~/mongodb]$ ls

mongo mongodump mongofiles mongorestore mongosniff

mongod mongoexport mongoimport mongos

只需要解压到相关目录即可,不需要编译安装

MongoDB启动与关闭:

mongoDB的服务器端程序为mongod

[falcon@ ~/mongodb]$ bin/mongod --help

** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data

** see /post/137788967/32-bit-limitations for more

Allowed options:

General options:

-h [ --help ] show this usage information

--version show version information

-f [ --config ] arg configuration file specifying additional options

--port arg specify port number

--bind_ip arg local ip address to bind listener - all local ips

bound by default

-v [ --verbose ] be more verbose (include multiple times for more

-vvvvv)

--dbpath arg (=/data/db/) directory for datafiles 指定数据存放目录

--quiet quieter output 静默模式

--logpath arg file to send all output to instead of stdout 指定日志存放目录

--logappend appnd to logpath instead of over-writing 指定日志是以追加还是以覆盖的方式写入日志文件

--fork fork server process 以创建子进程的方式运行

--cpu periodically show cpu and iowait utilization 周期性的显示cpu和io的使用情况

--noauth run without security 无认证模式运行

--auth run with security 认证模式运行

--objcheck inspect client data for validity on receipt 检查客户端输入数据的有效性检查

--quota enable db quota management 开始数据库配额的管理

--quotaFiles arg number of files allower per db, requires --quota 规定每个数据库允许的文件数

--appsrvpath arg root directory for the babble app server

--nocursors diagnostic/debugging option 调试诊断选项

--nohints ignore query hints 忽略查询命中率

--nohttpinterface disable http interface 关闭http接口,默认是28017

--noscripting disable scripting engine 关闭脚本引擎

--noprealloc disable data file preallocation 关闭数据库文件大小预分配

--smallfiles use a smaller default file size 使用较小的默认文件大小

--nssize arg (=16) .ns file size (in MB) for new databases 新数据库ns文件的默认大小

--diaglog arg 0=off 1=W 2=R 3=both 7=W+some reads 提供的方式,是只读,只写,还是读写都行,还是主要写+部分的读模式

--sysinfo print some diagnostic system information 打印系统诊断信息

--upgrade upgrade db if needed 如果需要就更新数据库

--repair run repair on all dbs 修复所有的数据库

--notablescan do not allow table scans 不运行表扫描

--syncdelay arg (=60) seconds between disk syncs (0 for never) 系统同步刷新磁盘的时间,默认是60s

Replication options:

--master master mode 主复制模式

--slave slave mode 从复制模式

--source arg when slave: specify master as 当为从时,指定主的地址和端口

--only arg when slave: specify a single database to replicate 当为从时,指定需要从主复制的单一库

--pairwith arg address of server to pair with

--arbiter arg address of arbiter server 仲裁服务器,在主主中和pair中用到

--autoresync automatically resync if slave data is stale 自动同步从的数据

--oplogSize arg size limit (in MB) for op log 指定操作日志的大小

--opIdMem arg size limit (in bytes) for in memory storage of op ids指定存储操作日志的内存大小

Sharding options:

--configsvr declare this is a config db of a cluster 指定shard中的

配置服务器

--shardsvr declare this is a shard db of a cluster 指定shard服务器

在启动mongoDB之前,我们必须新建一个存放mongoDB数据和日志的目录

[falcon@ ~]$ mkdir m_data m_log

到此mongodb启动的准备工作做完了,现在我们启动mongodb

[falcon@ ~/mongodb]$ bin/mongod --dbpath=/home/falcon/m_data

--logpath=/home/falcon/m_log --logappend &

现在mongodb启动了,检查是否启动的方法:

[falcon@ ~/mongodb]$ ps -ef|grep mongod

falcon 2533 2271 0 08:21 pts/0 00:00:00 bin/mongod

--dbpath=/home/falcon/m_data --logpath=/home/falcon/m_log --logappend

falcon 2541 2271 0 08:22 pts/0 00:00:00 grep mongod

查看mongodb的端口是否启动,默认是28017,在启动服务器时,可以通过--port来指定

[falcon@ ~/mongodb]$ netstat -an -t|grep 28017

tcp 0 0

0.0.0.0:28017 0.0.0.0:* LISTEN

到此,证明mongoDB已经启动完成

关闭的方法很简单:

Killall mongod 或者是 kill [pid]

使用方法:

利用客户端程序mongo登录mongoDB

[falcon@ ~/mongodb]$ bin/mongo

MongoDB shell version: 1.2.4-

url: test

connecting to: test

type "help" for help

> help

HELP

Show dbs 显示数据库名

show collections 显示当前数据库中的集合集

show users 显示当前数据库的用户

show profile 显示最后系统用时大于1ms的系统概要

use 切换到数据库

() help on DB methods

() help on collection methods

() list objects in collection foo

( { a : 1 } ) list objects in foo where a == 1

it result of the last line evaluated; use to

further iterate

> show dbs 默认情况下有2数据库

admin

local

> use admin 切换到admin数据库

switched to db admin

> show collections 显示admin数据库下面的集合集

s

下面我们来简单的新建集合集,插入、更新、查询数据,体验mongodb带给我们不一样的生活

新建数据库的方法是在

新建集合集:

> Collection("user");

{ "ok" : 1 }

> show collections

s

user

>

查入数据:

> ({uid:1,username:"Falcon.C",age:25});

> ({uid:2,username:"aabc",age:24});

查询数据:

> ();

{ "_id" : ObjectId("4b81e74c1f0fd3b9545cba43"), "uid" : 1, "username" : "Falcon.C",

"age" : 25 }

{ "_id" : ObjectId("4b81e74d1f0fd3b9545cba44"), "uid" : 2, "username" : "aabc",

"age" : 24 }

查询数据的方式很丰富,有类似于SQL的条件查询,将会在以后的文档中详细介绍

如:我想查询uid为1的用户信息

> ({uid:1});

{ "_id" : ObjectId("4b81e74c1f0fd3b9545cba43"), "uid" : 1, "username" : "Falcon.C",

"age" : 25 }

等等,丰富的查询还有limit ,sort ,findOne,distinct等

更新数据:

> ({uid:1},{$set:{age:26}})

> ();

{ "_id" : ObjectId("4b81e76f1f0fd3b9545cba45"), "uid" : 1, "username" : "Falcon.C",

"age" : 26 }

{ "_id" : ObjectId("4b81e7701f0fd3b9545cba46"), "uid" : 2, "username" : "aabc",

"age" : 24 }

> ({uid:1},{$inc:{age:-1}})

> ();

{ "_id" : ObjectId("4b81e76f1f0fd3b9545cba45"), "uid" : 1, "username" : "Falcon.C",

"age" : 25 }

{ "_id" : ObjectId("4b81e7701f0fd3b9545cba46"), "uid" : 2, "username" : "aabc",

"age" : 24 }

>

出了以上的2种用法,更新的条件还有$unset、$push 、$pushAll 、$pop 、$pull 、$pullAll

以上就是MongoDB简单的使用介绍,在以后的文档中将会详细的介绍mongoDB非常酷的CURD方法,mongoDB的Replication及分布式

开发文档:/display/DOCS/Developer+Zone

管理文档:/display/DOCS/Admin+Zone

下载地址:/display/DOCS/Downloads

MongoDB主从复制介绍(二)

MongoDB的主从复制其实很简单,就是在运行主的服务器上开启mongod进程时,加入参数--master即可,在运行从的服务器上开启mongod进程时,加入--slave 和 --source 指定主即可,这样,在主数据库更新时,数据被复制到从数据库中

(这里日志文件和访问数据时授权用户暂时不考虑)

下面我在单台服务器上开启2deamon来模拟2台服务器进行主从复制:

$ mkdir m_master m_slave

$mongodb/bin/mongod --port 28018 --dbpath ~/m_master --master &

$mongodb/bin/mongod --port 28019 --dbpath

~/m_slave --slave --source localhost:28018 &

这样主从服务器都已经启动了,可以利用netstat -an -t 查看28018、28019端口是否开放

登录主服务器:

$ mongodb/bin/mongo --port 28018

MongoDB shell version: 1.2.4-

url: test

connecting to: 127.0.0.1:28018/test

type "help" for help

> show dbs

admin

local

test

> use test

switched to db test

> show collections

这里主上的test数据什么表都没有,为空,查看从服务器同样也是这样

$ mongodb/bin/mongo --port 28019

MongoDB shell version: 1.2.4-

url: test

connecting to: 127.0.0.1:28019/test

type "help" for help

> show dbs

admin

local

test

> use test

switched to db test

> show collections

那么现在我们来验证主从数据是否会像想象的那样同步呢?

我们在主上新建表user

> db

test

>Collection("user");

> show collections

s

user

>

表user已经存在了,而且test库中还多了一个s用来存放索引的表

到从服务器上查看test库:

> db

test

> show collections

s

User

> ();

>

从服务器的test库中user表已经存在,同时我还查了一下user表为空

现在我们再来测试一下,向主服务器test库的user表中插入一条数据

> show collections

s

user

> ({uid:1,name:"Falcon.C",age:25});

> ();

{ "_id" : ObjectId("4b8226a997521a578b7aea38"), "uid" : 1, "name" : "Falcon.C",

"age" : 25 }

>

这时我们查看从服务器的test库user表时会多出一条记录来:

> ();

{ "_id" : ObjectId("4b8226a997521a578b7aea38"), "uid" : 1, "name" : "Falcon.C",

"age" : 25 }

>

MongoDB还有 Replica Pairs 和 Master - Master

参考地址:/display/DOCS/Master+Slave

MongoDB主主复制介绍(三)

MongoDB一般情况下都可以支持主主复制,但是在大部分情况下官方不推荐使用

运行的master - master的准备工作是:

新建存放数据库文件的路径

$mkdir mongodata/mm_28050 mongodata/mm_28051

运行mongodb数据库,一个端口为:28050,一个为:28051

$ mongodb/bin/mongod --port 28050 --dbpath ~/mongodata/mm_28050 --master --slave

--source localhost:28051 > /dev/null &

$ mongodb/bin/mongod --port 28051 --dbpath ~mongodata/mm_28051 --master --slave

--source localhost:28050 > /dev/null &

可以通过ps -ef|grep mongod 或 netstat -an -t来检查是否运行功能

测试master - master模式:

$ mongodb/bin/mongo --port 28050

MongoDB shell version: 1.2.4-

url: test

connecting to: 127.0.0.1:28050/test

type "help" for help

> show dbs

admin

local

> db

test

> ({_id:1,username:"Falcon.C",age:25,sex:"M"});

> ();

{ "_id" : 1, "username" : "Falcon.C", "age" : 25, "sex" : "M" }

> (); //在28051端口插入数据后,再来查询,看数据是否同步

{ "_id" : 1, "username" : "Falcon.C", "age" : 25, "sex" : "M" }

{ "_id" : 2, "username" : "NetOne", "age" : 24, "sex" : "F" }

>

$ mongodb/bin/mongo --port 28051

MongoDB shell version: 1.2.4-

url: test

connecting to: 127.0.0.1:28051/test

type "help" for help

> db

test

> show collections 端口28050已经新建了一个user表并插入了一条数据,这里多出2表

s

user

> (); //查询表user发现数据已经同步

{ "_id" : 1, "username" : "Falcon.C", "age" : 25, "sex" : "M" }

> ({_id:2,username:"NetOne",age:24,sex:"F"});在此插入数据看数据是否双向同步

> ();

{ "_id" : 1, "username" : "Falcon.C", "age" : 25, "sex" : "M" }

{ "_id" : 2, "username" : "NetOne", "age" : 24, "sex" : "F" }

>

通过以上开启两终端分别连接到28050、28051端口,分别插入测试数据发现,一切正常,正如我们所想的那样实现数据的双向同步

参考信息:/display/DOCS/Master+Master+Replication

MongoDB的使用技巧(四)

如果想查看当前连接在哪个数据库下面,可以直接输入db

> db

Admin

想切换到test数据库下面

> use test

switched to db test

> db

Test

想查看test下有哪些表或者叫collection,可以输入

> show collections

s

user

想知道mongodb支持哪些命令,可以直接输入help

> help

HELP

show dbs show database names

show collections show collections in current database

show users show users in current database

show profile show most recent e entries with

time >= 1ms

use set curent database to

() help on DB methods

() help on collection methods

() list objects in collection foo

( { a : 1 } ) list objects in foo where a == 1

it result of the last line evaluated; use to

further iterate

如果想知道当前数据库支持哪些方法:

> ();

DB methods:

r(username, password) 添加数据库授权用户

(username, password) 访问认证

atabase(fromhost) 克隆数据库

dHelp(name) returns the help for the command

tabase(fromdb, todb, fromhost) 复制数据库

Collection(name, { size : ..., capped : ..., max : ... } ) 创建表

tOp() displays the current operation in the db

tabase() 删除当前数据库

(func, args) run code server-side

lection(cname) same as db['cname'] or

lectionNames() 获取当前数据库的表名

tError() - just returns the err msg string

tErrorObj() - return full status object

go() get the server connection object

go().setSlaveOk() allow this connection to read from the

nonmaster member of a replica pair

e()

vError()

filingLevel()

licationInfo()

terDB(name) get the db at the same server as this onew

() kills the current operation in the db

ollectionStats() 打印各表的状态信息

eplicationInfo() 打印主数据库的复制状态信息

laveReplicationInfo() 打印从数据库的复制状态信息

hardingStatus() 打印分片状态信息

User(username) 删除数据库用户

Database() 修复数据库

rror()

mand(cmdObj) run a database command. if cmdObj is a string,

turns it into { cmdObj : 1 }

filingLevel(level) 0=off 1=slow 2=all

wnServer()

n() current version of the server

如果想知道当前数据库下的表或者表collection支持哪些方法,可以使用一下命令如:

> (); user为表名

DBCollection help

() 统计表的行数

ze() 统计表数据的大小

ct( key ) - eg. ct( 'x' ) 按照给定的条件除重

() drop the collection 删除表

dex(name) 删除指定索引

dexes() 删除所有索引

Index(keypattern,options) - options should be an object with

these possible fields: name, unique, dropDups 增加索引

( [query] , [fields]) - first parameter is an optional query

filter. second parameter is optional set of fields to return. 根据条件查找数据

e.g. ( { x : 77 } , { name :

1 , x : 1 } )

(...).count()

(...).limit(n) 根据条件查找数据并返回指定记录数

(...).skip(n)

(...).sort(...) 查找排序

e([query]) 根据条件查询只查询一条数据

() get DB object associated with collection 返回表所属的库

exes() 显示表的所有索引

( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) 根据条件分组

uce( mapFunction , reduceFunction , )

(query) 根据条件删除数据

Collection( newName ) renames the collection 重命名表

(obj) 保存数据

() 查看表的状态

eSize() - includes free space allocated to this collection

查询分配到表空间大小

ndexSize() - size in bytes of all the indexes 查询所有索引的大小

ize() - storage allocated for all data and indexes 查询表的总大小

(query, object[, upsert_bool]) 根据条件更新数据

te() - SLOW 验证表的详细信息

rdVersion() - only for use with sharding

Mongodb的备份工具mongodump

如果想备份数据库test 如:

[falcon@ ~/mongodb/bin]$ ./mongodump --help

options:

--help produce help message

-h [ --host ] arg mongo host to connect to

-d [ --db ] arg database to use

-c [ --collection ] arg collection to use (some commands)

-u [ --username ] arg username

-p [ --password ] arg password

--dbpath arg directly access mongod data files in this path,

instead of connecting to a mongod instance

-v [ --verbose ] be more verbose (include multiple times for more

-vvvvv)

-o [ --out ] arg (=dump) output directory

[falcon@ ~/mongodb/bin]$ [color=Blue]./mongodump -d test -o

test/[/color]

connected to: 127.0.0.1

DATABASE: test to test/test

to test/test/

100000 objects

s to test/test/

1 objects

[falcon@ ~/mongodb/bin]$ ls

2 mongo mongodump mongofiles mongorestore mongosniff

dump mongod mongoexport mongoimport mongos test

MongoDB的数据恢复工具mongorestore

查看test库中的表

> show collections

s

User

删除user表

> ();

True

> show collections

s

现在利用mongorestore表恢复刚才利用mongodump备份的数据

[falcon@ ~/mongodb/bin]$ ./mongorestore --help

usage: ./mongorestore [options] [directory or filename to restore from]

options:

--help produce help message

-h [ --host ] arg mongo host to connect to

-d [ --db ] arg database to use

-c [ --collection ] arg collection to use (some commands)

-u [ --username ] arg username

-p [ --password ] arg password

--dbpath arg directly access mongod data files in this path,

instead of connecting to a mongod instance

-v [ --verbose ] be more verbose (include multiple times for more

-vvvvv)

[falcon@ ~/mongodb/bin]$ ./mongorestore -d test -c user

test/test/

connected to: 127.0.0.1

test/test/

going into namespace []

100000 objects

User表中的10w条记录已经恢复

> show collections

s

user

> ();

{ "_id" : ObjectId("4b9c8db08ead0e3347000000"), "uid" : 1, "username" :

"Falcon.C-1" }

{ "_id" : ObjectId("4b9c8db08ead0e3347010000"), "uid" : 2, "username" :

"Falcon.C-2" }

{ "_id" : ObjectId("4b9c8db08ead0e3347020000"), "uid" : 3, "username" :

"Falcon.C-3" }

{ "_id" : ObjectId("4b9c8db08ead0e3347030000"), "uid" : 4, "username" :

"Falcon.C-4" }

{ "_id" : ObjectId("4b9c8db08ead0e3347040000"), "uid" : 5, "username" :

"Falcon.C-5" }

.................

has more

mongodb还提供了HTTP查看运行状态及restfull的接口

默认的访问端口是28017

rest的访问接口

参考地址:/display/DOCS/Http+Interface

MongoDB的sharding功能(五)

MongoDB的auto-sharding功能是指mongodb通过mongos自动建立一个水平扩展的数据库集群系统,将数据库分表存储在sharding的各个节点上。

一个mongodb集群包括一些shards(包括一些mongod进程),mongos路由进程,一个或多个config服务器

Shards

每一个shard包括一个或多个服务和存储数据的mongod进程(mongod是MongoDB数据的核心进程)

典型的每个shard开启多个服务来提高服务的可用性。这些服务/mongod进程在shard中组成一个复制集

Chunks

Chunk是一个来自特殊集合中的一个数据范围,(collection,minKey,maxKey)描叙一个chunk,它介于minKey和maxKey范围之间。

例如chunks 的maxsize大小是100M,如果一个文件达到或超过这个范围时,会被切分到2个新的chunks中。当一个shard的数据过量时,chunks将会被迁移到其他的shards上。同样,chunks也可以迁移到其他的shards上

Config Servers

Config服务器存储着集群的metadata信息,包括每个服务器,每个shard的基本信息和chunk信息

Config服务器主要存储的是chunk信息。每一个config服务器都复制了完整的chunk信息。

配置:(模拟2个shard服务和一个config服务)

Shard1:27020

Shard2:27021

Config:27022

Mongos启动时默认使用的27017端口

新建存放数据的目录

[falcon@ ~/mongodata]$ mkdir 27020 27021 27022

[falcon@ ~/mongodata]$ ls

27020 27021 27022

[falcon@ ~/mongodb/bin]$ ./mongod --dbpath

/home/falcon/mongodata/27020 --port 27020 > /home/falcon/mongodata/ &

[falcon@ ~/mongodb/bin]$ ./mongod --dbpath

/home/falcon/mongodata/27021 --port 27021 > /home/falcon/mongodata/ &

[falcon@ ~/mongodb/bin]$ ./mongod --dbpath

/home/falcon/mongodata/27022 --port 27022 > /home/falcon/mongodata/ &

启动mongos时,默认开启了27017端口

[falcon@ ~/mongodb/bin]$ ./mongos --configdb localhost:27022 >

/home/falcon/mongodata/ &

检查是否启动

[falcon@ ~/mongodb/bin]$ ps -ef|grep mongo

falcon 2612 1 0 20:15 ? 00:00:00 ./mongod --dbpath

/home/falcon/mongodata/27020 --port 27020

falcon 2619 1 0 20:15 ? 00:00:00 ./mongod --dbpath

/home/falcon/mongodata/27021 --port 27021

falcon 2625 1 0 20:15 ? 00:00:00 ./mongod --dbpath

/home/falcon/mongodata/27022 --port 27022

falcon 2658 1 0 20:15 ? 00:00:00 ./mongos --configdb

localhost:27022

falcon 2804 2772 0 20:31 pts/0 00:00:00 bin/mongo

falcon 2847 2812 0 20:55 pts/2 00:00:00 grep mongo

[falcon@ ~/mongodb/bin]$

[falcon@ ~/mongodb/bin]$ netstat -an -t

Active Internet connections (servers and established)

Proto Recv-Q Send-Q Local Address Foreign

Address State

tcp 0 0

0.0.0.0:10022 0.0.0.0:* LISTEN

tcp 0 0

0.0.0.0:27017 0.0.0.0:* LISTEN

tcp 0 0

0.0.0.0:587 0.0.0.0:* LISTEN

tcp 0 0

0.0.0.0:27020 0.0.0.0:* LISTEN

tcp 0 0

0.0.0.0:27021 0.0.0.0:* LISTEN

tcp 0 0

0.0.0.0:27022 0.0.0.0:* LISTEN

......

tcp 0 0

0.0.0.0:28020 0.0.0.0:* LISTEN

tcp 0 0

0.0.0.0:28021 0.0.0.0:* LISTEN

tcp 0 0

0.0.0.0:28022 0.0.0.0:* LISTEN

tcp 0 0

127.0.0.1:631 0.0.0.0:* LISTEN

........

看到以上信息证明mongodb启动完整,对于开启的28020、28021、28022是对于的http接口

[falcon@ ~/mongodb/bin]$ ./mongo 默认连接到mongos上

MongoDB shell version: 1.2.4-

url: test

connecting to: test

type "help" for help

> show dbs

admin

config

Local

加入shard节点

> use admin

switched to db admin

> mand( { addshard : "localhost:27020", allowLocal : true } )

{"ok" : 1 , "added" : "localhost:27020"}

> mand( { addshard : "localhost:27021", allowLocal : true } )

{"ok" : 1 , "added" : "localhost:27021"}

> mand({listshards:1}); 查看shard节点列表

{

"shards" : [

{

"_id" : ObjectId("4b9cd380c33000afad27718e"),

"host" : "localhost:27020"

},

{

"_id" : ObjectId("4b9cd381c33000afad27718f"),

"host" : "localhost:27021"

}

],

"ok" : 1

}

新建自动切片的库user001:

> config = connect("localhost:27022")

> config = terDB("config")

> user001=terDB("user001");

user001

> mand({enablesharding:"user001"})

{ "ok" : 1 }

> hardingStatus();

--- Sharding Status ---

sharding version: { "_id" : ObjectId("4b9cd354c33000afad27718d"), "version" :

2 }

shards:

{ "_id" : ObjectId("4b9cd380c33000afad27718e"), "host" : "localhost:27020" }

{ "_id" : ObjectId("4b9cd381c33000afad27718f"), "host" : "localhost:27021" }

databases:

{ "name" : "admin", "partitioned" : false, "primary" : "localhost:27022",

"_id" : ObjectId("4b9cd3776693dcfa468dec13") }

{ "name" : "user001", "partitioned" : true, "primary" : "localhost:27021",

"_id" : ObjectId("4b9cde866693dcfa468dec17") }

my chunks

我们来在user001中新建表,插入数据

> use user001

switched to db user001

> Collection("user_001")

{ "ok" : 1 }

> show collections

s

user_001

> _({uid:1,username:"Falcon.C",sex:"男",age:25});

> _();

{ "_id" : ObjectId("4b9ce1a6c84d7f20576c4df1"), "uid" : 1, "username" : "Falcon.C",

"sex" : "男", "age" : 25 }

我们来看看user001库被分配到了哪个shard上

[falcon@ ~/mongodata]$ ls -R

.:

27020 27021 27022

./27020:

test.0 test.1 _tmp

./27020/_tmp:

./27021:

_tmp user.0 user001.0 user001.1 user.1

./27021/_tmp:

./27022:

config.0 _tmp

./27022/_tmp:

[falcon@ ~/mongodata]$

从以上的文件可以看出,user001被分配到了27021的shard上了,但是通过mongos路由,我们并感觉不到是数据存放在哪个shard的chunk上

Sharding的管理命令

>

db.$e({isdbgrid:1});

{ "isdbgrid" : 1, "hostname" : "", "ok" : 1 }

> db.$e({ismaster:1});

{ "ismaster" : 1, "msg" : "isdbgrid", "ok" : 1 }

> printShardingStatus(terDB("config"))

--- Sharding Status ---

sharding version: { "_id" : ObjectId("4b9cd354c33000afad27718d"), "version" :

2 }

shards:

{ "_id" : ObjectId("4b9cd380c33000afad27718e"), "host" : "localhost:27020" }

{ "_id" : ObjectId("4b9cd381c33000afad27718f"), "host" : "localhost:27021" }

databases:

{ "name" : "admin", "partitioned" : false, "primary" : "localhost:27022",

"_id" : ObjectId("4b9cd3776693dcfa468dec13") }

my chunks

{ "name" : "user001", "partitioned" : true, "primary" : "localhost:27021",

"_id" : ObjectId("4b9cde866693dcfa468dec17") }

my chunks

> use admin

switched to db admin

> mand({netstat:1})

{ "configserver" : "localhost:27022", "isdbgrid" : 1, "ok" : 1 }

>

参考信息:/display/DOCS/Sharding

MongoDB数据库的索引操作(六)

Mongodb数据库的索引操作很简单,只需要把作为条件的字段设置为索引即可

> use user

switched to db user

> show collections

s

u_info

u_setting

> (); 这是默认的索引(默认为_id为索引)

{ "name" : "_id_", "ns" : "user.u_info", "key" : { "_id" :

ObjectId("") } }

{ "name" : "_id_", "ns" : "user.u_setting", "key" : { "_id" :

ObjectId("") } }

>

> db.u_({uid:1,name:"Falcon.C",address:"Beijing"});

> db.u_({uid:2,name:"sexMan",address:"Wuhan"});

> db.u_();

{ "_id" : ObjectId("4b9cf280c84d7f20576c4df2"), "uid" : 1, "name" : "Falcon.C",

"address" : "Beijing" }

{ "_id" : ObjectId("4b9cf284c84d7f20576c4df3"), "uid" : 2, "name" : "sexMan",

"address" : "Wuhan" }

插入了2条记录,我们来把uid设置为索引字段:

> db.u_Index({uid:1});

> db.u_Index({name:1});

> ();

{ "name" : "_id_", "ns" : "user.u_info", "key" : { "_id" :

ObjectId("") } }

{ "name" : "_id_", "ns" : "user.u_setting", "key" : { "_id" :

ObjectId("") } }

{ "ns" : "user.u_info", "key" : { "uid" : 1 }, "name" : "uid_1" }

{ "ns" : "user.u_info", "key" : { "name" : 1 }, "name" : "name_1" }

>

这时我们看到多了刚才我们设置的那个字段,这样在查询的时候,如果查询条件有uid字段或name字段,则走索引来进行查询

有索引:

> db.u_({name:"Falcon.C"});

{ "_id" : ObjectId("4b9cf280c84d7f20576c4df2"), "uid" : 1, "name" : "Falcon.C",

"address" : "Beijing" }

> db.u_({name:"Falcon.C"}).explain();

{

"cursor" : "BtreeCursor name_1",

"startKey" : {

"name" : "Falcon.C"

},

"endKey" : {

"name" : "Falcon.C"

},

"nscanned" : 1,

"n" : 1,

"millis" : 0,

"allPlans" : [

{

"cursor" : "BtreeCursor name_1",

"startKey" : {

"name" : "Falcon.C"

},

"endKey" : {

"name" : "Falcon.C"

}

}

]

}

删除索引后:

> ();

{ "name" : "_id_", "ns" : "user.u_info", "key" : { "_id" :

ObjectId("") } }

{ "name" : "_id_", "ns" : "user.u_setting", "key" : { "_id" :

ObjectId("") } }

{ "ns" : "user.u_info", "key" : { "uid" : 1 }, "name" : "uid_1" }

{ "ns" : "user.u_info", "key" : { "name" : 1 }, "name" : "name_1" }

> db.u_dex("name_1")

{ "nIndexesWas" : 3, "ok" : 1 }

> db.u_({name:"Falcon.C"}).explain();

{

"cursor" : "BasicCursor",

"startKey" : {

},

"endKey" : {

},

"nscanned" : 2,

"n" : 1,

"millis" : 0,

"allPlans" : [

{

"cursor" : "BasicCursor",

"startKey" : {

},

"endKey" : {

}

}

]

}

> ();

{ "name" : "_id_", "ns" : "user.u_info", "key" : { "_id" :

ObjectId("") } }

{ "name" : "_id_", "ns" : "user.u_setting", "key" : { "_id" :

ObjectId("") } }

{ "ns" : "user.u_info", "key" : { "uid" : 1 }, "name" : "uid_1" }

通过以上可以看出,查询的条件中有索引时,查询走BtreeCursor 的索引,而没有索引时走BasicCursor

通常需要索引的字段是:

1.唯一键 _id 是默认被设置为索引的

2.需要被查找的字段应该建立索引,比如在find()里面的字段

3.需要被排序的字段应该建立索引。比如在sort()里面的字段

以上就是MongoDB的索引操作

MongoDB数据库的MapReduce简单操作(七)

MongoDB也简单的实现了MapReduce的功能来提供分布式的数据查询服务,MapReduce的分布是功能主要用在Shard上

mand(

{ mapreduce : ,

map : ,

reduce :

[, query : ]

[, sort : ]

[, limit : ]

[, out : ]

[, keeptemp: ]

[, finalize : ]

[, scope : ]

[, verbose : true]

}

);

下面是对MapReduce的简单测试

此例子来源于:/display/DOCS/MapReduce

>

({_id:1,tags:['dog','cat']});

> ({_id:2,tags:['cat']});

> ({_id:3,tags:['mouse','cat','dog']});

> ({_id:4,tags:[]});

> m = function(){

... h(

... function(z){

... emit(z,{count:1});

... }

... );

};

function () {

h(function (z) {emit(z, {count:1});});

}

> r=function(key,values){

... var total = 0;

... for(var i=0;i<;i++)

... total += values[i].count;

... return {count:total};

... };

function (key, values) {

var total = 0;

for (var i = 0; i < ; i++) {

total += values[i].count;

}

return {count:total};

}

> res=uce(m,r);

{

"result" : "uce_1268577545_1",

"timeMillis" : 25,

"counts" : {

"input" : 4,

"emit" : 6,

"output" : 3

},

"ok" : 1,

"ok" : 1,

}

> res

{

"result" : "uce_1268577545_1",

"timeMillis" : 25,

"counts" : {

"input" : 4,

"emit" : 6,

"output" : 3

},

"ok" : 1,

"ok" : 1,

}

> db[].find()

{ "_id" : "cat", "value" : { "count" : 3 } }

{ "_id" : "dog", "value" : { "count" : 2 } }

{ "_id" : "mouse", "value" : { "count" : 1 } }

> db[].drop()

true

> db[].find()

>

以下有几个MapReduce的参考例子:

/display/DOCS/MapReduce

/mongodb/mongo/ ... sts/mr_

/mongodb/mongo/blob/master/jstests/

/mongodb/mongo/blob/master/jstests/

/mongodb/mongo/blob/master/jstests/

/mongodb/mongo/blob/master/jstests/

/mongodb/mongo/blob/master/jstests/


本文标签: 数据 数据库 查询 支持

更多相关文章

Android开发者进阶:7个经典框架深入解析

1月前

UI 框架 阿里新开源Android库V - Layout:淘宝、天猫都在用的UI框架V- Layout 是阿里出品的基础 UI 框架,用于快速实现页面的复杂布局,在手机天猫 Android版 内广泛使用:

Windows 11的Linux和安卓子系统:微软引领生态融合新篇章!

27天前

微软开放的 Windows Subsystem for Android(WSA)是 Windows 11 原生的系统级组件,让你在电脑上直接运行 Android 应用,无需第三方模拟器。、。(

Windows 11引领潮流:Linux与安卓子系统的创新整合体验

27天前

微软开放的 Windows Subsystem for Android(WSA)是 Windows 11 原生的系统级组件,让你在电脑上直接运行 Android 应用,无需第三方模拟器。、。(

家庭网络提速宝典:路由器配置技巧全攻略!

26天前

一、设备:买一个路由器,如TP-LINK(TL-R402M)90元左右,有一个WAN口和四个LAN口,另加上两条的两端都钳有水晶头的网线。 二、接法:把插到台式机的网线水晶头(另一端已接ADSL的)的接到路由器的WAN口上,用

012-XMP数据处理:打造Adobe Flash Player内核的XMP架构

26天前

012-XMP数据处理 学习目标 通过本章学习,你将掌握:XMP标准理解 XMP元数据架构和结构 XMP命名空间和属性定义 XMP与其他元数据

Win10升级后共享打印机连不上,我慌了!

23天前

问题一:系统更新导致“SMB 1.0CIFS 文件共享支持”关闭 方法一:win+R打开运行界面,输入control,打开控制面板,接着点击卸载程序的功能,进入卸载页面,点击启用或者关闭Windows功能。将“SMB 1.0

360电话手表11X与11XAI:性能升级,安全守护升级

23天前

360 儿童电话手表 11X AI 升级版,主要是接入了 360 智脑大模型,支持 AI 语音助手问答,支持 AI 绘画、生成专属 AI 卡通头像进行社交等功能。 它还提供了一对一 AI 数字人老师功能,可以帮助孩子训练英语口

局域网中轻松搞定SQL Server 2008的访问问题

22天前

SQL Server 2008 设置局域网内访问 在设置外网访问SQL2008数据库之前,首先必须保证局域网内访问SQL2008没有问题。 那么,我们先来看看局域网内访问SQL2008数据库需要哪些步骤和设置,才能做到

Office 2007用户必知:如何让MathType 5.2与PPT 2007和谐共存

21天前

让office2007支持MathType5.2前言:Mathtype是日常文档编辑中最合适的数学公式编辑器,操作直观、可完成复杂嵌套。MS也曾购买起部分产品作为Office套件的必备组件,在Office 2007(版本12)发

在32位与64位之间:操作系统的内存与处理器挑战

20天前

64位系统和32位系统的区别:操作系统只是硬件和应用软件中间的一个平台 32位操作系统针对的32位的CPU设计 64位操作系统针对的64位的CPU设计 我们的CPU从原来的8位,16位,

VSCode图片加载失败?这里有快速解决方案!

20天前

问题描述:VSCode加载图片出错 在开发过程中,Visual Studio Code(VSCode)加载图片时可能出现错误,例如图片无法显示、路径无效或格式不支持。这类问题通常由文件路径、扩展支持或配置问题导致。以下将分析常

Mac小白也能学会:深度清理系统垃圾,加速效率

19天前

在日常使用苹果电脑(Mac)时,系统和应用会产生各种缓存文件来加速操作,但久而久之,这些文件会占用宝贵的存储空间,甚至引发系统卡顿或异常。如何高效地清理Mac的缓存和垃圾文件,让电脑重新回归流畅?本文将为你详细介绍几种实用方法。

解析Canon CR2文件:揭秘cr2 ifd0的关键

19天前

首先是8个字节的文件头。 CR2的前2个字节是"II",代表INTEL格式的存储顺序,即低字节在前,高字节在后。 接下来是固定的2个字节:0x2a00。 最后的4个字节的整数是指向第一个IFD(I

Windows应用数据开发实战:Windows 8环境下轻松上手

18天前

一、Application Data简介Applicaion Data相当于桌面应用的注册表,存储一些用户配置信息,如运行时状态,用户喜好等,需要注意的时, 当卸载应用时,这些数据会被删除,所以不要存储重要数

掌握SWF文件,驾驭Adobe Flash Player的无限可能

18天前

一、Application Data简介Applicaion Data相当于桌面应用的注册表,存储一些用户配置信息,如运行时状态,用户喜好等,需要注意的时, 当卸载应用时,这些数据会被删除,所以不要存储重要数

Windows应用数据揭秘:在Windows 8开发中构建个性化应用程序

18天前

一、Application Data简介Applicaion Data相当于桌面应用的注册表,存储一些用户配置信息,如运行时状态,用户喜好等,需要注意的时, 当卸载应用时,这些数据会被删除,所以不要存储重要数

Adobe Flash Player与SWF:一段从技术到应用的旅程

18天前

一、Application Data简介Applicaion Data相当于桌面应用的注册表,存储一些用户配置信息,如运行时状态,用户喜好等,需要注意的时, 当卸载应用时,这些数据会被删除,所以不要存储重要数

Go与Linux通信基础:strace与read操作的深入解读

18天前

大家好,我是码农先森。 前言 各种编程语言百花齐放、百家争鸣,但是 “万变不离其中”。对于网络通信而言,每一种编程语言的实现方式都不一样;但其实,调用的底层逻辑都是一样的。linux 系统底层向上提供了统一的 Sock

移动硬盘无法读取是怎么回事?解决方法看这里!_读取外置硬盘

16天前

在日常办公生活中,我们仅仅使用电脑的话,已经远远不够存储我们的重要数据,这时候我们会采用移动硬盘、U盘等外置数据储存设备。它们虽然都有着小巧的体积,但是能够存储大量的信息和数据,随时和电脑连接实现数据互通,给我们的电脑工作带来极大的便

DiskGenius靠谱吗?_diskgenius坏道检测准确吗

16天前

在数字化时代,数据的重要性不言而喻。无论是个人用户还是企业,每天都要和大量数据打交道。当我们面临磁盘管理或数据恢复的需求时,我们需要一款可靠的工具来帮助我们管理磁盘空间和恢复丢失的数据。DiskGenius作为一款广受欢迎的磁盘管理软

发表评论

全部评论 0
暂无评论