標籤:
#coding:utf-8__author__ = ‘hdfs‘import pymongofrom pymongo import MongoClientclient = MongoClient()client=MongoClient(‘10.0.0.9‘,27017)#串連mongodb資料庫client = MongoClient(‘mongodb://10.0.0.9:27017/‘)#指定資料庫名稱db = client.test_database#擷取非系統的集合db.collection_names(include_system_collections=False)#擷取集合名posts = db.posts#尋找單個文檔posts.find_one()#給定條件的一個文檔posts.find_one({"author": "Mike"})#使用ID尋找需要ObjectIDfrom bson.objectid import ObjectIdpost_id=‘5728aaa96795e21b91c1aaf0‘document = client.db.collection.find_one({‘_id‘: ObjectId(post_id)})import datetimenew_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)}]#插入多條記錄result = posts.insert_many(new_posts)#返回插入的IDresult.inserted_ids#遞迴集合for post in posts.find(): post#遞迴條件集合for post in posts.find({"author": "Mike"}): post#文檔的記錄數posts.count()#區間查詢d = datetime.datetime(2009, 11, 12, 12)for post in posts.find({"date": {"$lt": d}}).sort("author"): print post#給集合profiles建立索引 唯一索引result = db.profiles.create_index([(‘user_id‘, pymongo.ASCENDING)],unique=True)#查看索引資訊list(db.profiles.index_information())#user_profiles = [{‘user_id‘: 211, ‘name‘: ‘Luke‘},{‘user_id‘: 212, ‘name‘: ‘Ziltoid‘}]result = db.profiles.insert_many(user_profiles)#彙總查詢from pymongo import MongoClientdb = MongoClient(‘mongodb://10.0.0.9:27017/‘).aggregation_example#準備資料result = db.things.insert_many([{"x": 1, "tags": ["dog", "cat"]}, {"x": 2, "tags": ["cat"]}, {"x": 2, "tags": ["mouse", "cat", "dog"]}, {"x": 3, "tags": []}])result.inserted_ids‘‘‘{ "_id" : ObjectId("576aaa973e5269020848cc7c"), "x" : 1, "tags" : [ "dog", "cat" ] }{ "_id" : ObjectId("576aaa973e5269020848cc7d"), "x" : 2, "tags" : [ "cat" ] }{ "_id" : ObjectId("576aaa973e5269020848cc7e"), "x" : 2, "tags" : [ "mouse", "cat", "dog" ] }{ "_id" : ObjectId("576aaa973e5269020848cc7f"), "x" : 3, "tags" : [ ] }‘‘‘from bson.son import SON#$unwind 解開-後面的變數pipeline = [ {"$unwind": "$tags"}, {"$group": {"_id": "$tags", "count": {"$sum": 1}}}, {"$sort": SON([("count", -1), ("_id", -1)])} ]list(db.things.aggregate(pipeline))#使用彙總函式with commanddb.command(‘aggregate‘, ‘things‘, pipeline=pipeline, explain=True)
python操作mongodb之基礎操作