我试图通过使用pymongo在for循环中插入一个dict到mongodb。但是我收到了一个错误
InvalidDocument:无法编码对象:1509261251
但是,当我选择一个dict输出并将其插入for循环外的mongodb时,它可以工作。我不知道为什么。
这是代码:
for i in range(len(re_kw)):
# read the column
kw = re_kw.iloc[i]['keywords']
# Models' prediction
re_kw.loc[re_kw['_id'] == re_kw.iloc[i]['_id']].copy()
re_kw.loc[:, '1'] = sportModel([kw])
re_kw.loc[:, '5'] = healthyModel([kw])
re_kw.loc[:, '17'] = sportModel([kw])
re_kw.loc[:, '38'] = musicModel([kw])
# Output results to mongoDB
dic = re_kw.iloc[i].to_dict()
coll = db['topics']
coll.insert_one(dic)
---------------------------------------------------------------------------
InvalidDocument Traceback (most recent call last)
<ipython-input-154-96f38b789987> in <module>()
13 dic = re_kw.iloc[i].to_dict()
14 coll = db['topics']
---> 15 coll.insert_one(dic)
16
17
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\collection.py in
insert_one(self, document, bypass_document_validation, session)
681 self._insert(document,
682 bypass_doc_val=bypass_document_validation,
--> 683 session=session),
684 self.write_concern.acknowledged)
685
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\collection.py in
_insert(self, docs, ordered, check_keys, manipulate, write_concern, op_id,
bypass_doc_val, session)
597 return self._insert_one(
598 docs, ordered, check_keys, manipulate,
write_concern, op_id,
--> 599 bypass_doc_val, session)
600
601 ids = []
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\collection.py in
_insert_one(self, doc, ordered, check_keys, manipulate, write_concern,
op_id, bypass_doc_val, session)
577
578 result = self.__database.client._retryable_write(
--> 579 True, _insert_command, session)
580 _check_write_command_response(result)
581 else:
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\mongo_client.py in
_retryable_write(self, retryable, func, session)
1100 """Internal retryable write helper."""
1101 with self._tmp_session(session) as s:
-> 1102 return self._retry_with_session(retryable, func, s,
None)
1103
1104 def __reset_server(self, address):
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\mongo_client.py in _retry_with_session(self, retryable, func, session, bulk)
1077 # Reset the transaction id and retry the operation.
1078 session._retry_transaction_id()
-> 1079 return func(session, sock_info, retryable)
1080 except ServerSelectionTimeoutError:
1081 if is_retrying():
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\collection.py in _insert_command(session, sock_info, retryable_write)
574 session=session,
575 client=self.__database.client,
--> 576 retryable_write=retryable_write)
577
578 result = self.__database.client._retryable_write(
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\pool.py in command(self, dbname, spec, slave_ok, read_preference, codec_options, check, allowable_errors, check_keys, read_concern, write_concern, parse_write_concern_error, collation, session, client, retryable_write, publish_events)
520 # Catch socket.error, KeyboardInterrupt, etc. and close ourselves.
521 except BaseException as error:
--> 522 self._raise_connection_failure(error)
523
524 def send_message(self, message, max_doc_size):
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\pool.py in _raise_connection_failure(self, error)
675 _raise_connection_failure(self.address, error)
676 else:
--> 677 raise error
678
679 def __eq__(self, other):
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\pool.py in command(self, dbname, spec, slave_ok, read_preference, codec_options, check, allowable_errors, check_keys, read_concern, write_concern, parse_write_concern_error, collation, session, client, retryable_write, publish_events)
515 self.max_bson_size, read_concern,
516 parse_write_concern_error=parse_write_concern_error,
--> 517 collation=collation)
518 except OperationFailure:
519 raise
~\Anaconda3\envs\ztdl\lib\site-packages\pymongo\network.py in command(sock, dbname, spec, slave_ok, is_mongos, read_preference, codec_options, session, client, check, allowable_errors, address, check_keys, listeners, max_bson_size, read_concern, parse_write_concern_error, collation)
100
101 request_id, msg, size = message.query(flags, ns, 0, -1, spec,
--> 102 None, codec_options, check_keys)
103
104 if (max_bson_size is not None
InvalidDocument: Cannot encode object: 1509261251
这是我把它放在try-except块中并打印字典的代码。
try:
for i in range(len(df)):
# 讀取欄位
kw = df.iloc[i]['keywords']
# 預測各分群結果
df.loc[df['_id'] == df.iloc[i]['_id']].copy()
df.loc[:, '1'] = sportModel([kw])
df.loc[:, '5'] = healthyModel([kw])
df.loc[:, '17'] = sportModel([kw])
df.loc[:, '38'] = musicModel([kw])
# 輸出資料至 mongoDB
dic = df.iloc[i].to_dict()
coll = db['topics']
coll.insert_one(dic)
except:
print(dic)
我不能把这个词放在这里因为stackoverflow说身体不能包含&#34;&#34;所以我把它放在下面的评论中。