日期:2014-05-16  浏览次数:20549 次

mongodb 1: 把玩把玩

这里对mongodb做一些初步认识

当然首先得启动服务和mongo shell

/usr/local/mongodb/bin/mongod --dbpath /home/yangdong/data/db
/usr/local/mongodb/bin/mongo
?

1、实例一个数据库
>use sample?? #sample不存在会创建一个
>db???????????????? #这里指向sample

> use sample
switched to db sample
> db
sample
?


2、集合(表)

#创建

user = {"name":"nico", "age":30, "gender":"male"}
db.users.insert(user)
#如果没有集合users会创建,并插入文档user数据

> user = {"name":"nico", "age":30, "gender":"male"}
{ "name" : "nico", "age" : 30, "gender" : "male" }
> db.users.insert(user)
?


#查看
db.users.find()?????????????? #读取所有文档
db.users.findOne()??????? #读取一个文档

> db.users.find()
{ "_id" : ObjectId("4f54747222eb23a50e4f5db5"), "name" : "nico", "age" : 30, "gender" : "male" }
> db.users.findOne()
{
    "_id" : ObjectId("4f54747222eb23a50e4f5db5"),
    "name" : "nico",
    "age" : 30,
    "gender" : "male"
}
?


#更新
user.address = "chengdu"
db.users.update({"name":"nico"}, user)
db.users.find()

> user.address = "chengdu"
chengdu
> db.users.update({"name":"nico"}, user)
> db.users.find()
{ "_id" : ObjectId("4f54747222eb23a50e4f5db5"), "name" : "nico", "age" : 30, "gender" : "male", "address" : "chengdu" }
> 
?




#删除
#删除文档
db.users.remove({"name":"aaa"})
db.users.remove()

> db.users.remove({"name":"aaa"})
> db.users.find()
{ "_id" : ObjectId("4f54747222eb23a50e4f5db5"), "name" : "nico", "age" : 30, "gender" : "male", "address" : "chengdu" }
> db.users.remove()
> db.users.find()
> 
?


以上操作在pymongo中实现

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pymongo import Connection

#get a connection
connection = Connection('localhost', 27017)

#show all databases
print connection.database_names()

#instance a new db
db = connection['sample']

#get a collection --> table
users = db.users

user = {"name":"nico", "age":30, "gender":"male"}
users.insert(user)

#读取所有文档
datas = users.find()
for user in datas:
    print user

#读取一个文档
print users.find_one()


#update
users.update({"name":"nico"}, {"$set":{"address":"chengdu"}})
print users.find_one()

#remove document
users.remove()
?

?