参考文档
一.安装和启动Mongodb
apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 echo 'deb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list apt-get update apt-get install mongodb-10gen /etc/init.d/mongodb start pip install pymongo mongo
二.常用操作
show dbs:显示数据库列表 show collections:显示当前数据库中的集合(类似关系数据库中的表) show users:显示用户 use <db name>:切换当前数据库,这和MS-SQL里面的意思一样 use test_database 创建或使用数据库 db.createCollection("people")创建表 db; 查看当前使用的数据库 db.stats(); 显示当前db状态 db.version(); 当前db版本 db.getMongo(); 查看当前db的链接机器地址 db.createCollection(“collName”, {size: 20, capped: 5, max: 100});创建一个聚集集合(table) db.getCollection("account");得到指定名称的聚集集合(table) db.getCollectionNames();得到当前db的所有聚集集合 db.addUser("name");添加一个用户 db.addUser("userName", "pwd123", true); 添加用户、设置密码、是否只读 db.userInfo.distinct("name");查询去掉后的当前聚集集合中的某列的重复数据,会过滤掉name中的相同数据 db.userInfo.find({"age": 22});查询age = 22的记录 db.userInfo.find({age: {$gt: 22}});查询age > 22的记录 db.userInfo.find().sort({age: 1}); 按照年龄升序: db.userInfo.find().sort({age: -1});按照年龄降序: db.userInfo.find({name: 'zhangsan', age: 22});查询name = zhangsan, age = 22的数据 db.userInfo.find().limit(5);查询前5条数据 db.userInfo.find({age: {$gte: 25}}).count();查询某个结果集的记录条数 db.users.save({name: ‘zhangsan’, age: 25, sex: true});修改、添加、删除集合数据 db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);修改 db.users.remove({age: 132});删除 db.Account.remove(); 全部删除
三.python 操作
#!/usr/bin/env python from pymongo import Connection if __name__ == "__main__": con=Connection() db=con.test_database people=db.people people.insert({'name':'Mike','food':'cheese'}) people.insert({'name':'John','food':'ham','location':'UK'}) people.insert({'name':'michelle','food':'cheese'}) peeps =people.find() print "INSERT & FIND TEST" for person in peeps: print person peeps =people.find({'food':'cheese'}) print "FIND WITH DICT TEST" for person in peeps: print person peeps = people.find({'name':{'$regex':'.*[Mm]i.*'}}) print 'REGEX TEST' for person in peeps: print person person=people.find_one({'food':'ham'}) person['food']='eggs' people.save(person) print "UPDATE RECORD TEST" for person in people.find({'food':'eggs'}): print person for person in people.find(): people.remove(person)