mongoDB - 日常操作四
生活随笔
收集整理的這篇文章主要介紹了
mongoDB - 日常操作四
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
python 使用 mongodb
easy_install pymongo# 安裝(python2.7+)
import pymongo connection=pymongo.Connection('localhost',27017) # 創建連接 db = connection.test_database # 切換數據庫 collection = db.test_collection # 獲取collection # db和collection都是延時創建的,在添加Document時才真正創建
文檔添加, _id自動創建
import datetime post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()} posts = db.posts posts.insert(post) ObjectId('...')?
批量插入
new_posts = [{"author": "Mike", "text": "Another post!", "tags": ["bulk", "insert"], "date": datetime.datetime(2009, 11, 12, 11, 14)}, {"author": "Eliot", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime.datetime(2009, 11, 10, 10, 45)}] posts.insert(new_posts) [ObjectId('...'), ObjectId('...')]?
獲取數據
獲取所有collection db.collection_names() # 相當于SQL的show tables獲取單個文檔 posts.find_one()?
?
數據查詢
查詢多個文檔 for post in posts.find(): post加條件的查詢 posts.find_one({"author": "Mike"})高級查詢 posts.find({"date": {"$lt": "d"}}).sort("author")?
統計數量
posts.count()?
加索引
from pymongo import ASCENDING, DESCENDING posts.create_index([("date", DESCENDING), ("author", ASCENDING)])?
查看查詢語句的性能
posts.find({"date": {"$lt": "d"}}).sort("author").explain()["cursor"] posts.find({"date": {"$lt": "d"}}).sort("author").explain()["nscanned"]轉載于:https://www.cnblogs.com/sharesdk/p/8688533.html
總結
以上是生活随笔為你收集整理的mongoDB - 日常操作四的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: webservice入门程序学习中经验总
- 下一篇: 51Nod 1294 修改数组 —— L