Python操作MongoDB(PyMongo模組的使用)

來源:互聯網
上載者:User

標籤:upd   ring   odi   .so   username   des   串連數   時間   bin   

#!/usr/bin/env python #coding:utf-8 # Author:   --<qingfengkuyu> # Purpose: MongoDB的使用 # Created: 2014/4/14 #32位的版本最多隻能儲存2.5GB的資料(NoSQLFan:最大檔案尺寸為2G,生產環境推薦64位)  import pymongo import datetime import random  #建立串連 conn = pymongo.Connection( ‘10.11.1.70‘ , 27017 ) #串連資料庫 db = conn.study #db = conn[‘study‘]  #列印所有聚集名稱,串連聚集 print u ‘所有聚集:‘ ,db.collection_names() posts = db.post #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) #posts.insert(new_posts)#批量插入多條資料  #刪除記錄 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():#查詢全部記錄 #for item in posts.find({"UserName":"urling"}):#查詢指定記錄 #for item in posts.find().sort("UserName"):#查詢結果根據UserName排序,預設為升序 #for item in posts.find().sort("UserName",pymongo.ASCENDING):#查詢結果根據UserName排序,ASCENDING為升序,DESCENDING為降序 for item in posts.find().sort([( "UserName" ,pymongo.ASCENDING),( ‘date‘ ,pymongo.DESCENDING)]): #查詢結果根據多列排序      print item  #查看查詢語句的效能 #posts.create_index([("UserName", pymongo.ASCENDING), ("date", pymongo.DESCENDING)])#加索引 print posts.find().sort([( "UserName" ,pymongo.ASCENDING),( ‘date‘ ,pymongo.DESCENDING)]).explain()[ "cursor" ] #未加索引用BasicCursor查詢記錄 print posts.find().sort([( "UserName" ,pymongo.ASCENDING),( ‘date‘ ,pymongo.DESCENDING)]).explain()[ "nscanned" ] #查詢語句執行時查詢的記錄數

Python操作MongoDB(PyMongo模組的使用)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.