mongodbgomongodb-querydrivermongo-go

How to Set Limit for options.FindOne() in go mongo-driver


I see there is a way to SetLimit() for Find() func, But I don't see any options to set limit for FindOne() , Since we are searching single result out of FindOne() we don't even have to limit it ? Automatically it handles limit ?

Tried setting limit using 1options.FindOne()` , But I do not see a way to do that .


Solution

  • It's not documented, but it's common sense that Collection.FindOne() implies a behavior of that of Limit=1. The return value of Collection.FindOne() doesn't give access to multiple result documents, that's why options.FindOne doesn't even have a SetLimit() method.

    If you check the source code, it's in there:

    // Unconditionally send a limit to make sure only one document is returned and the cursor is not kept open
    // by the server.
    findOpts = append(findOpts, options.Find().SetLimit(-1))
    

    Note that FindOptions.Limit documents that:

    // Limit is the maximum number of documents to return. The default value is 0, which means that all documents matching the
    // filter will be returned. A negative limit specifies that the resulting documents should be returned in a single
    // batch. The default value is 0.
    Limit *int64