from pymongo.objectid import ObjectId ImportError: No module named objectid

寵の児 提交于 2019-12-08 10:17:20

问题


I made an python code that fetch tweets from Mongo collection called Tweets. I wan't to fetch only the object text and add an additional object called Sentiment.

When i loop through the Tweets and parse the json object to a string i get the error :

from pymongo.objectid import ObjectId ImportError: No module named objectid

Therefor i use the following code

import pymongo
import nltk
import json
from json import JSONEncoder
from pymongo import MongoClient
from pymongo.objectid import ObjectId

#JSON Encoder
class MongoEncoder(JSONEncoder):
    def default(self, obj, **kwargs):
        if isinstance(obj, ObjectId):
            return str(obj)
        else:            
            return JSONEncoder.default(obj, **kwargs)

#Mongo Settings
client = MongoClient()
db = client.Sentiment
Tweets = db.Tweet
TweetTraining = db.TweetTraining

#GET TEXT_TAG FROM TWEET
for tweet in Tweets.find({"lang":"nl"},{"text"}):
  print json.dumps(tweet, cls=MongoEncoder)

I hope that you can help me out. Many thanks

Erik


回答1:


One of the imports at the top of your file is incorrect. ObjectId should be loaded from bson.objectid instead of pymongo.objectid

from bson.objectid import ObjectId

Here is a link to the pymongo documentation for querying by ObjectId

PyMongo - Querying By ObjectId



来源:https://stackoverflow.com/questions/28251835/from-pymongo-objectid-import-objectid-importerror-no-module-named-objectid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!