回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我试图用PyMongo将一个文档(本例中是twitter信息)插入到Mongo数据库中。</p>
<p>如下所示,tweets\u listdt[0]与</p>
<pre><code>{
'created_at': u'Sun Aug 03 17:07:24 +0000 2014',
'id': 2704548373,
'name': u'NoSQL',
'text': u'RT @BigdataITJobs: Data Scientist \u2013 Machine learning, Python, Pandas, Statistics @adam_rab in London, United Kingdom http://t.co/pIIJVPCuN8\u2026'
}
</code></pre>
<p>但我无法将tweets_listdt[0]保存到我的Mongodb中,而我可以使用后面的一个。</p>
<pre><code>In[529]: tweets_listdt[0] == {'created_at': u'Sun Aug 03 17:07:24 +0000 2014',
'id': 2704548373,
'name': u'NoSQL',
'text': u'RT @BigdataITJobs: Data Scientist \u2013 Machine learning, Python, Pandas, Statistics @adam_rab in London, United Kingdom http://t.co/pIIJVPCuN8\u2026'}
Out[528]: **True**
</code></pre>
<p>这个失败了:</p>
<pre><code>In[530]: tweetsdb.save(tweets_listdt[0])
tweetsdb.save({'created_at': u'Sun Aug 03 17:07:24 +0000 2014',
'id': 2704548373,
'name': u'NoSQL',
'text': u'RT @BigdataITJobs: Data Scientist \u2013 Machine learning, Python, Pandas, Statistics @adam_rab in London, United Kingdom http://t.co/pIIJVPCuN8\u2026'})
Traceback (most recent call last):
File "D:\Program Files\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 3035, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-529-b1b81c04d5ad>", line 1, in <module>
tweetsdb.save(tweets_listdt[0])
File "D:\Program Files\Anaconda\lib\site-packages\pymongo\collection.py", line 1903, in save
check_keys, manipulate, write_concern)
File "D:\Program Files\Anaconda\lib\site-packages\pymongo\collection.py", line 430, in _insert
gen(), check_keys, self.codec_options, sock_info)
InvalidDocument: **Cannot encode object: 2704548373**
</code></pre>
<p>这个没问题:</p>
<pre><code>In[531]: tweetsdb.save({'created_at': u'Sun Aug 03 17:07:24 +0000 2014',
'id': 2704548373,
'name': u'NoSQL',
'text': u'RT @BigdataITJobs: Data Scientist \u2013 Machine learning, Python, Pandas, Statistics @adam_rab in London, United Kingdom http://t.co/pIIJVPCuN8\u2026'})
Out[530]: **ObjectId('554b38d5c3d89c09688b1149')**
</code></pre>
<h3>5/10更新</h3>
<p>谢谢伯尼。我使用的PyMongo版本是3.0.1。</p>
<p>下面是对id数据类型的检查:</p>
<pre><code>In[36]:type(tweets_listdt[0]['id'])
Out[37]:long
</code></pre>
<p>如果我只是使用:</p>
<pre><code>for tweet in tweets_listdt:
tweetsdb.save(tweet)
</code></pre>
<p>会发生上述错误。</p>
<p>但如果我再加上这句话,一切都很好:</p>
<pre><code>tweet['id'] = int(tweet['id'])
</code></pre>
<p>当我直接指派</p>
<pre><code>tweets_listdtw = {'created_at': u'Sun Aug 03 17:07:24 +0000 2014',
'id': 2704548373,
'name': u'NoSQL',
'text': u'RT @BigdataITJobs: Data Scientist'}
</code></pre>
<p><strong>tweetsdb.save(tweets\u listdtw)</strong>正在工作,并且</p>
<pre><code>print type(tweets_listdtw['id'])
<type 'numpy.int64'>
</code></pre>
<p>又弄糊涂了。。。所以长类型当然是可以的……但是为什么在我把'id'改成int之后,保存就生效了?</p>