How to classification "null" field in FindIterator<Document>

21 views
Skip to first unread message

THakim

unread,
Jan 8, 2018, 7:41:43 AM1/8/18
to mongodb-dev
Hallo All, I am try find data in my collection use FindIterator<Document>, but data could not found with parameter or data not exist  in collection and how to skip logic if i cannot find data in my collection ?

ex :
public DocumentBio findOneBiotCollectionById(ObjectId idBio) {
     
       
        if (idBio != null) {
           
            FindIterable<DocumentBio> findOneBioDoc = bioCollection.find(Filters.eq("_id", idBio));
       
            MongoCursor<DocumentBio> itConsignmentColl = findOneBioDoc.iterator();

                 
                for (ConsignmentDoc loopDataConsign : itConsignmentColl) {
                    Debug.print("loopdataConsign print out "+loopDataConsign);
                    return loopDataConsign;
                }
           }
        }

Jeff Yemin

unread,
Jan 8, 2018, 10:43:44 AM1/8/18
to mongodb-dev
The Java driver idiom for finding a single document is to use the MongoIterable#first method, as in:

    return bioCollection.find(Filters.eq(idBio)).first();


This will return the document with _id equal to idBio if it's found, and otherwise return null.


Regards,
Jeff

Monika Shah

unread,
Jan 10, 2018, 7:07:16 AM1/10/18
to mongodb-dev
Does it work to match any field(other than _id)?

Jeff Yemin

unread,
Jan 10, 2018, 9:18:07 AM1/10/18
to mongodb-dev
You can use any filter you want, but the idiom only makes sense when you know that only the first result is of interest, e.g.
  • an equality match on a unique index
  • combined with sort criteria where you only are interested in the first document returned

Regards,
Jeff
Reply all
Reply to author
Forward
0 new messages