Get position of selected document in collection [mongoDB] Get position of selected document in collection [mongoDB] mongodb mongodb

Get position of selected document in collection [mongoDB]


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 documentsthat 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.


As far as I know, there is no single command to do this, and this is impossible in general case (see Derick's answer). However, using count() for a query done on an ordered id value field seems to work. Warning: this assumes that there is a reliably ordered field, which is difficult to achieve in a concurrent writer case. In this example _id is used, however this will only work with a single writer case.:

MongoDB shell version: 2.0.1connecting to: test> use so_testswitched to db so_test> db.example.insert({name: 'A'})> db.example.insert({name: 'B'})> db.example.insert({name: 'C'})> db.example.insert({name: 'D'})> db.example.insert({name: 'E'})> db.example.insert({name: 'F'})> db.example.find(){ "_id" : ObjectId("4fc5f040fb359c680edf1a7b"), "name" : "A" }{ "_id" : ObjectId("4fc5f046fb359c680edf1a7c"), "name" : "B" }{ "_id" : ObjectId("4fc5f04afb359c680edf1a7d"), "name" : "C" }{ "_id" : ObjectId("4fc5f04dfb359c680edf1a7e"), "name" : "D" }{ "_id" : ObjectId("4fc5f050fb359c680edf1a7f"), "name" : "E" }{ "_id" : ObjectId("4fc5f053fb359c680edf1a80"), "name" : "F" }> db.example.find({_id: ObjectId("4fc5f050fb359c680edf1a7f")}){ "_id" : ObjectId("4fc5f050fb359c680edf1a7f"), "name" : "E" }> db.example.find({_id: {$lte: ObjectId("4fc5f050fb359c680edf1a7f")}}).count()5> 

This should also be fairly fast if the queried field is indexed. The example is in mongo shell, but count() should be available in all driver libs as well.


This might be very slow but straightforward method. Here you can pass as usual query. Just I am looping all the documents and checking if condition to match the record. Here I am checking with _id field. You can use any other single field or multiple fields to check it.

var docIndex = 0;db.url_list.find({},{"_id":1}).forEach(function(doc){  docIndex++;  if("5801ed58a8242ba30e8b46fa"==doc["_id"]){    print('document position is...' + docIndex);    return false;  }});