Get position of selected document in collection [mongoDB]

Saint picture Saint · May 30, 2012 · Viewed 16.1k times · Source

How to get position (index) of selected document in mongo collection?

E.g. this document: db.myCollection.find({"id":12345}) has index 3 in myCollection

myCollection:
    id: 12340, name: 'G'
    id: 12343, name: 'V'
    id: 12345, name: 'A'
    id: 12348, name: 'N'

Answer

DhruvPathak picture DhruvPathak · May 30, 2012

If your requirement is to find the position of the document irrespective of any order, that is not possible as MongoDb does not store the documents in specific order. However,if you want to know the index based on some field, say _id , you can use this method.

If you are strictly following auto increments in your _id field. You can count all the documents that have value less than that _id, say n , then n + 1 would be index of the document based on _id.

n = db.myCollection.find({"id": { "$lt" : 12345}}).count() ;

This would also be valid if documents are deleted from the collection.