1
2
|
[root@localhost ~]
# pip install pymongo
[root@localhost ~]
# yum install -y mongodb-server
|
1
|
[root@localhost ~]
# mongod --dbpath=/data/mongodb/db/--logpath=/data/mongodb/mongodb.log
|
1
|
[root@localhost ~]
# yum install -y python-pip
|
1
|
[root@localhost ~]
# python
|
1
2
3
4
5
|
>>> from pymongo
import
*
>>> client = MongoClient()
//
与以下两种方式等同
>>> client = MongoClient(“localhost”, 27017)
>>> client = MongoClient(“mongodb:
//localhost
:27017/”)
|
1
2
|
>>> db = client.test_db
>>> collection = db.test_collection
|
1
2
3
4
5
6
7
|
>>> mydict = {“name”:”Lucy”, “sex”:”female”,”job”:”nurse”}
>>> collection.insert(mydict)
>>> collection.insert_one(mydict)
>>> collection.insert_many(mydict)
//
会报错,.insert_many()时参数必须为 list 形式,做如下包装:
>>> mylist = []
>>> mylist.append(mydict)
>>> collection.insert_many(mylist)
//
不会报错
|
1
2
3
|
>>> collection.
find
({“name”:”Lucy”})[0]
>>> collection.
find
({“name”:”Lucy”})[1]
……
|
1
2
3
4
5
|
>>>
for
i
in
collection.
find
({“name”:”Lucy”})
… print i
…
{u
'job'
: u
'nurse'
, u
'_id'
: ObjectId(
'554bd2e1e1382306bba8ade9'
),u
'name'
: u
'Lucy'
, u
'sex'
: u
'female'
}
{u
'nationality'
: u
'US'
, u
'age'
: 24, u
'_id'
: ObjectId(
'554be1cce138230714d0ab0d'
),u
'name'
: u
'Lucy'
}
|
1
2
|
>>> collection.find_one({“name”:”Lucy”})
>>> collection.find_one({“name”:”Lucy”, “sex”:”female”})
|
1
2
|
>>> collection.
find
().count()
//
等同于collection.count()
>>> collection.
find
({“name”:”Lucy”}).count()
|
1
|
>>> collection.
find
({“age”: {“$lt”: 30}})
|
1
2
3
|
>>> collection.
find
().
sort
(
"age"
)
//
默认,升序
>>> collection.
find
().
sort
(
"age"
, pymongo.ASCENDING)
//
升序
>>> collection.
find
().
sort
(
"age"
, pymongo.DESCENDING)
//
降序
|
1
2
|
>>> db.collection_names()
>>> db.collection_names(include_system_collections=Flase)
//
不包括系统collection,一般指的是system.indexes
|
1
2
3
4
5
|
>>> temp = collection.find_one({
"name"
:
"Lucy"
})
>>> temp2 = temp.copy()
>>> temp[
"name"
] =
"Jordan"
>>> collection.save(temp)
//
或 .update() ,注意参数形式
>>> collection.update(temp, temp2)
//
将temp更新为temp2
|
1
|
>>> collection.replace_one(old_document, new_document)
|
1
2
3
|
>>> collection.remove(temp)
//
即便该temp不存在也不会报错
>>> collection.delete_one(temp)
>>> collection.delete_many(temp)
//
与 .insert_many() 不同,在temp不是list类型时也不会报错
|
1
2
3
4
|
>>>
import
json
>>>
for
i
in
collection.
find
(“{“name”:”Lucy”})
… del i[“_id”]
//
不能直接转换,无法识别ObjectId
… json.dumps(i)
|
1
2
3
4
5
6
7
|
>>> from bson
import
Binary, Code
>>> from bson.json_util
import
dumps
>>> dumps([{
'foo'
: [1, 2]},
... {
'bar'
: {
'hello'
:
'world'
}},
... {
'code'
: Code(
"function x() { return1; }"
)},
... {
'bin'
: Binary(
""
)}])
'[{"foo": [1, 2]}, {"bar": {"hello":"world"}}, {"code": {"$code": "function x(){ return 1; }", "$scope": {}}}, {"bin":{"$binary": "", "$type": "00"}}]'
|