-1

I have created several documents and inserted into Mongo DB.I am using python for the same . Is there a way where in I can get the _id of a particular record? I know that we get the _id during insertion. But if i need to use it at a lateral interval is there a way I can get it by say using the find() command?

TheFallenOne
  • 1,598
  • 2
  • 23
  • 57

3 Answers3

0

You can user the projection to get particular field from the document like this

db.collection.find({query},{_id:1}) this will return only _id

http://docs.mongodb.org/manual/reference/method/db.collection.find/

Rohit Jain
  • 2,052
  • 17
  • 19
0

In python, you can use the find_one() method to get the document and access the _id property as following:

def get_id(value):
    # Get the document with the record:
    document = client.db.collection.find_one({'field': value}, {'_id': True})
    return document['_id']
chridam
  • 100,957
  • 23
  • 236
  • 235
0

When you insert the record, you can specify the _id value. This has added benefits for when you're using ReplicaSets as well.

from pymongo.objectid import ObjectId

client.db.collection.insert({'_id': ObjectId(), 'key1': value....})    

You could store those Ids in a list and use it later on if your requirement for needing the _id occurs immediately after insert.

justcompile
  • 3,362
  • 1
  • 29
  • 37