原文:http://blog.csdn.net/luoweifeng1989/article/details/6571965

安装Mongo数据库:

  

    第一步:下载安装包:官方下载地址←单击此处,如果是win系统,注意是64位还是32位版本的,请选择正确的版本。

    第二步:新建目录“D:\MongoDB”,解压下载到的安装包,找到bin目录下面全部.exe文件,拷贝到刚创建的目录下。

    第三步:在“G:\MongoDb”目录下新建“data”文件夹,它将会作为数据存放的根文件夹。

  配置Mongo服务端:(WIN7)

  打开CMD窗口,按照如下方式输入命令:
  > d:
  > cd G:\MongoDb
  > mongod --dbpath G:\MongoDb\DBData

 

1、在使用mongo数据库前,需要启动该数据库,我的数据库是在D:\html5work\mongodb-win32-i386-2.0.2-rc1\bin下,运行,CMD,cd到这个目录下,输入D:\html5work\mongodb-win32-i386-2.0.2-rc1\bin>mongod --dbpath D:\html5work\db,数据库即启动。(这个过程可做成一个服务)

这边注意,mongod是服务端的命令,客户端的命令是mongo。

2、再次运行CMD,cd到D:\html5work\mongodb-win32-i386-2.0.2-rc1\bin>目录下,现在准备在客户端使用数据库。

3、一些命令

/*数据库状态信息查询*/

> db.serverStatus()

输出参数为json格式有几个主要的类型:

 uptime: 服务器运行时间(秒)

 localTime: 服务器本地时间

 mem: 服务器内存信息

 connections: 当前连接数

 opcounters: 操作统计

/*查看所有数据库:*/

> show dbs

/*切换数据库:*/

>use locationDb

switched to db locationDb

>db.stats()

/*创建数据库*/

MongoDB没有创建数据库的命令,可以使用use dbname进行切换,use可以切换到不存在的数据库,当有数据写入的时候就会创建数据库。

>use mytestdb

创建Collection

进入数据库建立coolection数据库才算建立完成。使用

db.createCollection("mytestdb ", {capped:true, size:10000}) 单位是kb

或者db.runCommand( {createCollection:" mytestdb ", capped:true, size:100000} )

capped参数是建立固定大小的数据库文件,为了保证效率,mongo会在建立collection的时候占用磁盘空间,防止碎片。

> db.createCollection("mytestdb ", {capped:true, size:10000})

> show collections

mytestdb

建立文档

>db. mytestdb.insert({name:'xiaowanzi',age:8})

示例查询

操作符

SQL

Mongo

*

Select * from mytestdb

db.mytestdb.find()

Column

Select name,age from mytestdb

db.mytestdb.find({},{name:1,age:1})

Where *

Select * from mytestdb where age=24

db.mytestdb.find({age:24})

Column where

Select name,age from mytestdb where age=24

db.mytestdb.find({age:24},{name:1,age:1})

>> <<

Select * from mytestdb where age>20

db.mytestdb.find({‘age’:{>:20}})

Like

Select * from mytestdb where name like ‘wang%’

db.mytestdb.find({name:/^wangfan/})

Select * from mytestdb where name like ‘%wang%’

db.mytestdb.find({name:/wangfan/})

Order

SELECT * FROM mytestdb ORDER BY name DESC

db.mytestdb.find().sort({name:-1})

> db.mytestdb.find()

{ "_id" : ObjectId("4e093ff90edf95f31cbc7c29"), "name" : "xiaowanzi", "age" : 8 }

创建索引

使用ensureIndex来创建索引

db. mytestdb.ensureIndex({name:1})

db.runCommand({dropIndexes:'foo', index : '*'})

这里的1是正序,-1是倒序

删除索引

db.collection.dropIndexes();删除所有的索引

db. mytestdb.dropIndexes({name:1});

db.runCommand({dropIndexes:'wfcoll', index : {name:1}})

我们在name字段做一个索引,在age上做个负索引,如下:

>db.mytestdb.ensureIndex({name:1})

>db.mytestdb.ensureIndex({age:-1})