import
pymongo
import
datetime
import
random
conn
=
pymongo.Connection(
'10.11.1.70'
,
27017
)
db
=
conn.study
print
u
'所有聚集:'
,db.collection_names()
posts
=
db.post
print
posts
new_post
=
{
"AccountID"
:
22
,
"UserName"
:
"libing"
,
'date'
:datetime.datetime.now()}
new_posts
=
[{
"AccountID"
:
22
,
"UserName"
:
"liuw"
,
'date'
:datetime.datetime.now()},
{
"AccountID"
:
23
,
"UserName"
:
"urling"
,
'date'
:datetime.datetime.now()}]
posts.insert(new_post)
print
u
'删除指定记录:\n'
,posts.find_one({
"AccountID"
:
22
,
"UserName"
:
"libing"
})
posts.remove({
"AccountID"
:
22
,
"UserName"
:
"libing"
})
posts.update({
"UserName"
:
"urling"
},{
"$set"
:{
'AccountID'
:random.randint(
20
,
50
)}})
print
u
'记录总计为:'
,posts.count(),posts.find().count()
print
u
'查询单条记录:\n'
,posts.find_one()
print
posts.find_one({
"UserName"
:
"liuw"
})
print
u
'查询多条记录:'
for
item
in
posts.find().sort([(
"UserName"
,pymongo.ASCENDING),(
'date'
,pymongo.DESCENDING)]):
print
item
print
posts.find().sort([(
"UserName"
,pymongo.ASCENDING),(
'date'
,pymongo.DESCENDING)]).explain()[
"cursor"
]
print
posts.find().sort([(
"UserName"
,pymongo.ASCENDING),(
'date'
,pymongo.DESCENDING)]).explain()[
"nscanned"
]