最近、業務でpymongoを始めたので自分のメモとしての備忘録。 まずは、pymongoでDB接続:
1 2 3 4 5 | #! /usr/bin/env python # -*- coding: utf-8 -*- # pymongo import from pymongo import Connection from pymongo import MongoClient #外部mongoに接続するurl parser from pymongo.uri_parser import parse_uri uri = 'mongodb://-u:-p@mongo.server:xxxx/dbname conn = Connection(host=uri, slave_okay=True) params = parse_uri(uri) db = conn[params['database']] # local connect client = MongoClient('mongodb://localhost:27017') local_db = client[local_db_name] |
ReplicaSetで、secondary preferred にする。
1 2 3 4 5 6 | from pymongo import MongoClient from pymongo.read_preferences import ReadPreference conn = MongoClient("mongodb://u:p@morton.local:27017,morton.local:27018,\ morton.local:27019/db_name") conn.read_preference = ReadPreference.SECONDARY_PREFERRED db = conn['db_name'] |
次は、query.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | ##### Update ###### obj_to_be_updated = {"$set":{"x":y}} local_db[col_name].update({"a":a},obj_to_be_updated) #Upsert "update query に upsert=trueを引数に追加するだけ" obj_to_be_updated = {"$set":{"x":y}} local_db[col_name].update({"a":a},obj_to_be_updated, upsert=True) #Insert local_db[col_name].insert(data) ##### find ###### #find one field db[collection_name].find({'apikey':apikey}) #find more than one field db[col_name].find({'apikey':apikey,'item':x}) ##### sort ###### #sort by new to old db[col_name].find({'apikey':apikey}).sort('create_at',-1).limit(10) ##### if exists or not ###### local_db[col_name].find({"item":{'$exists':True}}) local_db[col_name].find({"item":{'$exists':False}}) ##### check the size (length of the array e.g {'x':[1,2,3,4]}) ###### local_db[col_name].find({"item": {'$size':1}}) ##### count ###### local_db[col_name].count({"item": {$exists:True}}) local_db[col_name].find({"item": {$exists:True}}).count() #### これはどっちでもいいのかな?#### ##### find the length of the array value in the field which is greater than x ##### ## This was a bit tricky because $size only takes integers ## db[col_name].find({item:{$exists:true},'$where':'this.item.length > 10'}) # 他にも、$gt, $lt, などなど。。。 |
まだまだ勉強中!!
references:
http://cookbook.mongodb.org/patterns/date_range/
http://api.mongodb.org/python/current/examples/high_availability.html#high-availability-and-mongos