python怎么操作mongodb

 我来答
育知同创教育
2017-11-03 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
展开全部
#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)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式