Trevor Burnham
Trevor Burnham

Reputation: 77416

How do I get the ID of an object after persisting it in PyMongo?

I have a PyMongo newbie question: If collection is a PyMongo Collection and I use it to save an object with

obj = {'foo': 'bar'}
collection.insert(obj)

then MongoDB automatically generates an _id field for obj; once can confirm this with

print obj

which yields something like

{'foo': 'bar', '_id': ObjectId('4c2fea1d289c7d837e000000')}

My question is: How do I get that _id back out in such a way that I can use it?

For instance, if I want to delete obj from the database, I would think that I would want to do something like

collection.remove(obj['_id'])

but when I try this I get the message

TypeError: 'ObjectId' object is unsubscriptable.

What's going on?

Upvotes: 5

Views: 6273

Answers (4)

Sagar Varpe
Sagar Varpe

Reputation: 3599

for removing a object from document you have to mention condition As you can specify "_id" for a document ........

_id = db.test.insert({"foo": "test"})
db.test.remove({"_id":_id})

Upvotes: -1

mdirolf
mdirolf

Reputation: 7651

insert returns the _id of the inserted document.

and remove will remove based on _id, so try something like:

doc_id = db.test.insert({"foo": 1})
db.test.remove(doc_id)

Upvotes: 3

kris
kris

Reputation: 23592

You just need to pass remove a dict, just like you did insert. So, to remove a document based on its _id value, do something like:

collection.remove({'_id': ObjectId('4c2fea1d289c7d837e000000')})

Upvotes: 12

Matthew Flaschen
Matthew Flaschen

Reputation: 284806

You can just pass obj.

Upvotes: 1

Related Questions