Neil
Neil

Reputation: 8247

How to convert mongoDB objectID to string in python

I am reading in data from mongoDB to pandas dataframe..

client = MongoClient('localhost',27017)
db = client.test_insert                     ## name of the database
collection = db.dataset2 

df = pd.DataFrame(list(db.dataset2.find()))

This will all the documents from dataset2 collection of mongoDB.. Then I am converting it to pandas data frame. Next I am storing last inserted objectID of document inserted..

last_inserted_id = df['_id'].tail(1)

Then I want to read in only new documents inserted in dataset2 collection.. I am trying to do it like this.

df2 = db.dataset2.find({"_id": {"$gt": ObjectId(last_inserted_id) }})

But it gives me an error

TypeError: id must be an instance of (str, unicode, ObjectId), not <class       
'pandas.core.series.Series'>

I converted data frames '_id' column into string but it doesn't work.. Gives me the same error.. How to do it? please help

Upvotes: 2

Views: 3635

Answers (1)

adamc
adamc

Reputation: 880

Have you tried this change to the call that throws the error?

df2 = db.dataset2.find({"_id": {"$gt": last_inserted_id }})

It seems like that's what you're trying to do. The last_inserted_id is the value to search; the ObjectId is a class, not a valid argument for that mongo find.

Upvotes: 1

Related Questions