V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Colorful
V2EX  ›  Python

请教下, Python 里插入 mongo 一直报错

  •  
  •   Colorful · 2020-01-11 12:51:03 +08:00 · 2486 次点击
    这是一个创建于 1560 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import pymongo
    from pymongo import MongoClient
    client = pymongo.MongoClient(host='127.0.0.1', port=27017)
    collection = client.newtext
    print('============',collection )

    class FirstPipeline(object):

    def process_item(self, item, spider):
    for i in range(0,len(item["content"])):
    arrtext = {'title':item['title'][i],'price':item["price"][i],'content':item["content"][i]}
    collection.insert_many(arrtext)
    return item



    这是 scapy 框架,在 pipelines.py 页面里面写的,上面是这个页面所有的代码

    打印出来的值是这样的

    Database(MongoClient(host=['127.0.0.1:27017'], document_class=dict, tz_aware=False, connect=True), 'newtext')

    菜鸟一枚
    8 条回复    2020-01-11 22:07:19 +08:00
    Nitroethane
        1
    Nitroethane  
       2020-01-11 12:56:08 +08:00 via iPad
    insert_many 的得是数组吧,保存字典应该用 insert_one (忘记了是 insert 还是 insert_one,看下文档就知道了)
    Colorful
        2
    Colorful  
    OP
       2020-01-11 13:01:07 +08:00
    @Nitroethane insert 也不行
    caly5144
        3
    caly5144  
       2020-01-11 13:27:47 +08:00
    同菜鸟,不过没有见过 client.newtext 这样的语法。我写的时候一般是
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["database"] # 创建 /连接数据库
    mycol = mydb["collection"] # 创建 /连接集合

    mycol.insert_one({}) # 插入一条数据
    JCZ2MkKb5S8ZX9pq
        4
    JCZ2MkKb5S8ZX9pq  
       2020-01-11 15:57:23 +08:00
    @Nitroethane 是 insert_one

    @caly5144 client.db 好像是可以,collection 我也是习惯用 db[collection],不过 lz 是不是少了一级? client.db.collection
    Nitroethane
        5
    Nitroethane  
       2020-01-11 16:00:26 +08:00
    @JCZ2MkKb5S8ZX9pq #4
    @Colorful #2

    行与不行倒是把返回值打印出来,有 exception 抛出的话把 exception 也贴出来,你一句也不行谁知道是什么问题
    littlespider89
        6
    littlespider89  
       2020-01-11 16:01:49 +08:00
    client.db.newtext.insert_one({...})
    JCZ2MkKb5S8ZX9pq
        7
    JCZ2MkKb5S8ZX9pq  
       2020-01-11 16:02:36 +08:00
    @Nitroethane 我看代码好像是少了一级,没有 collection,直接在 db.insert。
    Colorful
        8
    Colorful  
    OP
       2020-01-11 22:07:19 +08:00
    @JCZ2MkKb5S8ZX9pq 对的,找到原因了,就是少了一极的原因,太感谢各位大侠了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3033 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:11 · PVG 08:11 · LAX 17:11 · JFK 20:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.