简体   繁体   中英

How to find the first qualified document in mongodb using java?

How to find the first matching document in mongodb

I try to find matching document in mongodb collection. And I'm sure that there is only one matching document. But when I use the function find() in java, it tries to find all documents(if there were more) in a collection, which will make it slow.

Here is the code I wrote

Document documentForClassMessage=class_message.find(Filters.eq("class_id",class_id)).first();

Note: class_message's type is MongoCollection<Document>

I thought there would be a method findOne() in java since it exits in other language, but it didn't.

I want to know how to find one matching document in a collection and immediately finish searching when it have found or is there a faster way to search a matching document in a large collection?

Have you tried limit ?

class_message.find(Filters.eq("class_id",class_id)).limit(1)

I'm not completely sure about the syntax, as I haven't tried it in java.

Reference

From MongoDb Java docs

The find().first() construct is useful for queries that should only match a single document or if you are interested in the first document only.

The difference between limit and first is that limit will give you a cursor (you need to iterate over it to get document), while first will return the document itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM