python存入mongodb的几种方法

目录

1.一般方法存入MongoDB

2.定义函数存入MongoDB

3.在scrapy中存入MongoDB

4.从数据库中取数据

正文:

1.一般方法存入MongoDB

import pymongo

from pymongo.collection import Collection    #注意英文拼写

client= pymongo.MongoClient("localhost")

db= client['xxx']    #xxx为数据库名

id_Collection= Collection(db,'xxx')    #xxx为表名

id_Collection.insert("{xxx}")    #xxx为字典

2.定义函数存入MongoDB

import pymongo

def save_to_mongo(self,result):

    client= pymongo.MongoClient("xxx")    #联接客户端,本地写localhost,

    db= client["xxx"]    #数据库名称,按自己需求写一个

    db['xxx'].Insert(result)    #xxx为表名,result为要存的数据

3.在scrapy中存入MongoDB

#首先在setting中最下面加

mongo_host= "127.0.0.1"

mongo_port= 27017

mongo_db_name= "xxx"#xxx为数据库名称

mongo_db_collection= "xxx" #xxx为表名称

#然后在pipelines.py中

import pymongo

from xxx.settingsimport mongo_port

class xxxPipeline(object):

    def __init__(self):

        host= mongo_host

        port= mongo_port

        dbname= mongo_db_name

        sheetname= mongo_db_collection

        client= pymongo.MongoClient(host=host,port=port)

        mydb= client[dbname]

        self.post= mydb[sheetname]

def process_item(self,item,spider):

        data= dict(item)

        self.post.insert(data)

        return item

4.从mongodb数据库中取数据

import pymongo

from pymongo.collectionimport  Collection

client= pymongo.MongoClient("localhost:27017")

db= client['xxx']#xxx为数据库名

id_collection= Collection(db,'xxx')    #xxx为表名

task_id_collection.find_one_and_delete({})#查找一个并删除掉

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容