MongoDB简单介绍

MongoDB (from "humongous") 是一个可扩展的,高效的,面向文档的数据库。它的作用是介于关系数据库与key-value数据库之间的一种数据库。它具有如下几个特点:

  • 面向文档的存储结构:它底层是用一种叫JSON的结构来做为基本的存储单元,以此来提供动态的Schema,
  • 对任意属性的索引支持
  • 数据冗余与高可用性
  • 数据的自动分片
  • 丰富的查询模式
  • 支持Map/Reduce数据流处理
  • 基于GridFS的文件存储系统

2. Quickstart 64-bit linux

下载: 略

 

安装: 略

 

配置

mongodb.conf
dbpath=/duitang/data/mongodb
#bind_ip=192.168.172.8
logpath=/duitang/logs/mongodb/sys.log
logappend=true
fork = true

启动

mongod -f /duitang/dist/conf/mongodb/mongodb.conf

 

3. 一些简单的数据库操作语句

3.1 建立数据库连接

./mongo foo connects to the foo database on your local machine
./mongo 192.168.13.7/foo connects to the foo database on 192.168.13.7
./mongo dbserver.mydomain.com/foo connects to the foo database on dbserver.mydomain.com
./mongo 192.168.13.7:9999/foo connects to the foo database on 192.168.13.7 on port 9999

3.1插入数据

之前我以为需要先创建database,结果找了半天没有找到命令,原来第一次插入数据会自动创建数据库:

use shopping_item
data = {title:"nike",price:"98.99",sold:"59",status:"new",url:"http://detail.tmall.com/item.htm?spm=a1z10.1.w1036274.5.vDxCGX&id=14413088156",sourceType:"tmall",picUrl:"http://img02.taobaocdn.com/imgextra/i2/573736914/T2Gh1hXhRbXXXXXXXX_!!573736914.jpg",createDateTime:Date(),shop_id:1,catetory:"nike"}
db.taobaoitem.insert(data)
db.taobaoitem.find()

输出:

{ "_id" : ObjectId("5085011058871808a1856f9f"), "title" : "nike", "price" : "98.99", "sold" : "59", "status" : "new", "url" : "http://detail.tmall.com/item.htm?spm=a1z10.1.w1036274.5.vDxCGX&id=14413088156", "sourceType" : "tmall", "picUrl" : "http://img02.taobaocdn.com/imgextra/i2/573736914/T2Gh1hXhRbXXXXXXXX_!!573736914.jpg", "createDateTime" : "Mon Oct 22 2012 15:58:50 GMT+0800 (CST)", "shop_id" : 1, "catetory" : "nike" }

 这是的"_id"字段是数据库自动增加的。

 

批量插入:

for (var i = 1; i <= 20; i++)db.taobaoitem.insert(data)
 

3.3 数据查询

使用游标来操作数据集

var cursor = db.taobaoitem.find();
while (cursor.hasNext()) printjson(cursor.next());
 

返回指定的字段数据

db.taobaoitem.find({sold:"59"}).limit(3);

db.flashBar.find({}, {"tagId":1,"eventId":1})

 

OR查询

db.userInfo.find({$or: [{age: 22}, {age: 25}]});
 

3.4 删除数据库

 db.dropDatabase()
{ "dropped" : "shopping_item", "ok" : 1 }
 

3.x 相关资料

当然,MongoDB支持一些更加复杂的查询,如OR,AND,Group by等,可以参考如下

http://www.mongodb.org/display/DOCS/Manual

http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart

http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html

 

4. python客户端的介绍

4.1 安装

$ git clone git://github.com/mongodb/mongo-python-driver.git pymongo
$ cd pymongo/
$ python setup.py install

4.2 简单使用

>>> import pymongo import Connection
>>> connection = Connection()
你也可以指定IP与端口号
>>> connection = Connection('localhost',27017)
得到一个数据库
>>> db = connection.test_database
或者用这种方式 
>>> db = connection['test_database']
得到一个数据集
>>> collection = db.test_collection
插入数据
>>> post = {"author":"bob"}
>>> posts = db.posts
>>> posts.insert(post)/
输出所有posts表中的数据
>>> for post in posts.find():
>>>  	post
分页,排序
flashUnitColl.find(param, fields).sort(sort_cond, pymongo.DESCENDING).skip(int(page) * int(page_size)).limit(int(page_size))
删除
import bson
shopping_item_dao.remove({"_id":bson.objectid.ObjectId(id)})

like 和 OR 查询,分页:

    def query(self, query_param=None, order_param=None,page=0,page_size=15):
        '''
        查询
        query_param: 查询条件,{catetory:''}
        order_param: 排序条件(按照价格降序):{order_by:'price',order_type:'desc'} 
        '''
        param = {'status':'new'}          #默认查询条件
        order_by = '_id'    #默认排序规则
        order_type = pymongo.DESCENDING #默认排序规则
        
        if query_param:
            _ca = re.compile(query_param['catetory'])
            param['$or'] = [{'catetory':_ca,'title':_ca}]
        if order_param:    
            order_by = order_param['order_by'] 
            order_type = order_param['order_type']=='desc' and pymongo.DESCENDING or pymongo.ASCENDING
        return shopping_item_dao.find(param).sort(order_by, order_type).skip(int(page) * int(page_size)).limit(page_size)

  python API:http://api.mongodb.org/python/current/api/pymongo/cursor.html

修改操作:

flashBarColl.update({},{'$set':{eventId:41,tagId:135709}})
 

 

 

 

进入mogo client
mongo 127.0.0.1

显示帮助
help

查看有哪些数据库
show dbs 
admin 0.203125GB

使用某个db
use admin

查看db下的表
show collections
system.indexes
system.users

查询
db.system.users.find()
db.flashBar.find({}, {"tagId":1,"eventId":1})

修改

db.flashBar.update({eventId:40},{$set:{eventId:41,tagId:135709}},false










,true










)
db.unreadCount.update({notices:0},{$set:{notices:1}},false










,true










)



mongo支持like查询

	Pattern p = Pattern.compile(msg);
			Query cond = new Query(Criteria.where("msg").is(p)).limit(limit).skip(next);
			if (order == 0) {
				cond.sort().on("_id", Order.ASCENDING);
			} else {
				cond.sort().on("_id", Order.DESCENDING);
			}
			List<Comment> cmts = mongodbs.getBlogDB().find(cond, Comment.class);

 

 

Query Options

Field Selection

In addition to the query expression, MongoDB queries can take some additional arguments. For example, it's possible to request only certain fields be returned. If we just wanted the social security numbers of users with the last name of 'Smith,' then from the shell we could issue this query:

// retrieve ssn field for
 documents where last_name == 'Smith':

  db.users.find({last_name: 'Smith'}, {'ssn': 1});

  // retrieve all fields *except* the thumbnail field, for
 all documents:

  db.users.find({}, {thumbnail:0});
 

Note the _id field is always returned even when not explicitly requested.

Sorting

MongoDB queries can return sorted results. To return all documents and sort by last name in ascending order, we'd query like so:

db.users.find({}).sort({last_name: 1});
 
Skip and Limit

MongoDB also supports skip and limit for easy paging. Here we skip the first 20 last names, and limit our result set to 10:

db.users.find().skip(20).limit(10);
db.users.find({}, {}, 10, 20); // same as above, but less clear
 
slaveOk (Querying Secondaries)

When querying a replica set, drivers route their requests to the primary mongod by default; to perform a query against an (arbitrarily-selected) secondary, the query can be run with the slaveOk option. See the slaveOk page for more information.

Cursors

Database queries, performed with the find() method, technically work by returning a cursor . Cursors are then used to iteratively retrieve all the documents returned by the query. For example, we can iterate over a cursor in the mongo shell like this:

> var
 cur = db.example.find();
> cur.forEach( function(x) { print(tojson(x))});
{"n"
 : 1 , "_id"
 : "497ce96f395f2f052a494fd4"
}
{"n"
 : 2 , "_id"
 : "497ce971395f2f052a494fd5"
}
{"n"
 : 3 , "_id"
 : "497ce973395f2f052a494fd6"
}

更多文档参考:http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值