获取所选文档在集合中的位置[mongoDB] [英] Get position of selected document in collection [mongoDB]
问题描述
如何获取mongo集合中选定文档的位置(索引)?
How to get position (index) of selected document in mongo collection?
例如
本文档:db.myCollection.find({"id":12345})
在myCollection
myCollection:
id: 12340, name: 'G'
id: 12343, name: 'V'
id: 12345, name: 'A'
id: 12348, name: 'N'
推荐答案
如果您的要求是查找文档的位置,而不考虑任何顺序,那不是
可能的原因是MongoDb不会按特定顺序存储文档.
但是,如果您想基于某个字段(例如_id
)来了解索引,则可以使用此方法.
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.
如果您严格遵守_id
字段中的自动增量.您可以计算所有文件
其值小于_id
的值,例如n,则n +1将是基于_id
的文档的索引.
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.
这篇关于获取所选文档在集合中的位置[mongoDB]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!