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?
Asked
Active
Viewed 56 times
-1
-
Of course you can :) – sergiuz Oct 14 '15 at 23:21
-
@SergiuZaharie Please elaborate – TheFallenOne Oct 14 '15 at 23:27
-
what are you trying to do? Each document has an _id, of course you can search for a document and display its _id. – sergiuz Oct 14 '15 at 23:31
-
`_id` will be returned as part of the document when you use `find`. – dirn Oct 14 '15 at 23:31
-
http://stackoverflow.com/questions/25589113/how-to-select-a-single-field-in-mongodb This link provides the option to return selective fields. Is there any option to retrieve only the id field? @dirn – TheFallenOne Oct 14 '15 at 23:55
-
`Collection.findOne(query,{fields: {_id: 1}})` will get you just the `_id` – Michel Floyd Oct 15 '15 at 02:02
3 Answers
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