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

2020-01-11 12:51:03 +08:00
 Colorful
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')

菜鸟一枚
2544 次点击
所在节点    Python
8 条回复
Nitroethane
2020-01-11 12:56:08 +08:00
insert_many 的得是数组吧,保存字典应该用 insert_one (忘记了是 insert 还是 insert_one,看下文档就知道了)
Colorful
2020-01-11 13:01:07 +08:00
@Nitroethane insert 也不行
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
2020-01-11 15:57:23 +08:00
@Nitroethane 是 insert_one

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

行与不行倒是把返回值打印出来,有 exception 抛出的话把 exception 也贴出来,你一句也不行谁知道是什么问题
littlespider89
2020-01-11 16:01:49 +08:00
client.db.newtext.insert_one({...})
JCZ2MkKb5S8ZX9pq
2020-01-11 16:02:36 +08:00
@Nitroethane 我看代码好像是少了一级,没有 collection,直接在 db.insert。
Colorful
2020-01-11 22:07:19 +08:00
@JCZ2MkKb5S8ZX9pq 对的,找到原因了,就是少了一极的原因,太感谢各位大侠了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/637055

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX