python mongodb
博客专区 > hyhlinux 的博客 > 博客详情
python mongodb
hyhlinux 发表于11个月前
python mongodb
  • 发表于 11个月前
  • 阅读 18
  • 收藏 0
  • 点赞 0
  • 评论 0

华为云·免费上云实践>>>   

摘要: 1.insert 2.update 3.remove 4.map-reduce 5.ObjectID 6.时间处理

#coding:utf-8
import json
from pymongo import MongoClient
from datetime import datetime
from bson.code import Code

client = MongoClient(host='127.0.0.1', port=27017)
db = client.test
# #insert
# result = db.restaurants.insert_one(
#     {
#         "address": {
#             "street": "2 Avenue",
#             "zipcode": "10075",
#             "building": "1480",
#             "coord": [-73.9557413, 40.7720266]
#         },
#         "borough": "Manhattan",
#         "cuisine": "Italian",
#         "grades": [
#             {
#                 "date": datetime.strptime("2014-10-01", "%Y-%m-%d"),
#                 "grade": "A",
#                 "score": 11
#             },
#             {
#                 "date": datetime.strptime("2014-01-16", "%Y-%m-%d"),
#                 "grade": "B",
#                 "score": 17
#             }
#         ],
#         "name": "Vella",
#         "restaurant_id": "41704620"
#     }
# )
# print result.inserted_id

#query
cursor = db.restaurants.find({"borough": "Manhattan"})
ret = []
"""
{
u'cuisine': u'Italian', 
u'borough': u'Manhattan', 
u'name': u'Vella', 
u'restaurant_id': u'41704620', 
u'grades': [
    {
        u'date': datetime.datetime(2014, 10, 1, 0, 0), 
        u'grade': u'A', u'score': 11
    }, 
    {
        u'date': datetime.datetime(2014, 1, 16, 0, 0), 
        u'grade': u'B', u'score': 17
    }
], 
u'address': {
    u'building': u'1480', 
    u'street': u'2 Avenue', 
    u'zipcode': u'10075', 
    u'coord': [-73.9557413, 40.7720266]
}, 
u'_id': ObjectId('584d1239678f862910189391')
}
-------------
('ret', 
[
'{
    "cuisine": "Italian", 
    "borough": "Manhattan", 
    "name": "Vella", 
    "restaurant_id": "41704620", 
    "grades": [
        {"date": "2014-10-01 00:00:00", "grade": "A", "score": 11}, 
        {"date": "2014-01-16 00:00:00", "grade": "B", "score": 17}
    ], 
    "address": {
        "building": "1480", 
        "street": "2 Avenue", 
        "zipcode": "10075", 
        "coord": [-73.9557413, 40.7720266]
    }, 
    "_id": "584d1239678f862910189391"
}'
]
)
"""
for document in cursor:
    # del document['_id']
    document['_id'] = str(document['_id'])
    # del document['grades']
    for item in  document['grades']:
        # print ('item:', item)
        item['date'] = datetime.strftime(item['date'],'%Y-%m-%d %H:%M:%S')
    # print(document)
    item = json.dumps(document)
    ret.append(item)

print ('ret', ret)


# cursor = db.restaurants.find({"grades.grade": "B"})
# for document in cursor:
#   print(document)


# Logical AND
# cursor = db.restaurants.find({"cuisine": "Italian", "address.zipcode": "10075"})
# for document in cursor:
#     print(document)

# Logical OR
# cursor = db.restaurants.find(
#     {"$or": [{"cuisine": "Italian"}, {"address.zipcode": "10075"}]})


# for document in cursor:
#     print(document)

# Update Top-Level Fields

# result = db.restaurants.update_one(
#     {"name": "Vella"},
#     {
#         "$set": {
#             "cuisine": "American (New)"
#         },
#         "$currentDate": {"lastModified": True}
#     }
# )
# print result.matched_count
# result = db.restaurants.update_one(
#     {"restaurant_id": "41704620"},
#     {"$set": {"address.street": "East 31st Street"}}
# )
# print result.matched_count

# Remove Data with PyMongo
# result = db.restaurants.delete_many({"borough": "Manhattan"})
# print result.deleted_count
# result = db.restaurants.delete_many({})

# Data Aggregation with PyMongo
# cursor = db.restaurants.aggregate(
#     [
#         {"$group": {"_id": "$borough", "count": {"$sum": 1}}}
#     ]
# )
# for document in cursor:
#     print(document)

# map-reduce
db = client.mp
# result = db.restaurants.insert([
#     {
#         "_id":1,
#         "cust_id":'marong',
#         "status":'A',
#         "items":[{
#             "sku":'mmm',
#             "qty":5,
#             "price":2.5
#         },{
#             "sku":'nnn',
#             "qty":5,
#             "price":2.5
#         }]
#     },
#     {
#         "_id":2,
#         "cust_id":'marong',
#         "status":'B',
#         "items":[{
#             "sku":'mmm',
#             "qty":5,
#             "price":3
#         },{
#             "sku":'nnn',
#             "qty":5,
#             "price":3
#         }]
#     },
# ])
# print result
mapper=Code(
"""
function () {
var key = this.cust_id
var value = 0;
for (var idx = 0; idx < this.items.length; idx++){
   value += this.items[idx].qty * this.items[idx].price;
}
emit(key, value);
}
""")
reducer= Code(
"""
function (key, values) {
return Array.sum(values);
}
""")
# print mapper, reducer
# coursor = db.restaurants.map_reduce(map=mapper, reduce=reducer, out="map_reduce_example")

# print coursor
# for x in coursor.find():
#     print x
# Collection(Database(MongoClient(host=['tplinux.cn:27017'], document_class=dict, tz_aware=False, connect=True), u'mp'), u'map_reduce_example')
# {u'_id': u'marong', u'value': 55.0}


 

 

标签: python mongodb
共有 人打赏支持
粉丝 8
博文 130
码字总数 50509
×
hyhlinux
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: