Navigation

collection.findOne()

Definition

collection.findOne()

Return a single document from a collection or view. If multiple documents satisfy the query, this method returns the first document according to the query’s sort order or natural order.

Usage

Example

To call the collection.findOne() action from a Function, get a collection handle with database.collection() then call the handle’s findOne() method.

const query = { "quantity": { "$gte": 25 } };
const projection = {
 "title": 1,
 "quantity": 1,
}

return itemsCollection.findOne(query, projection)
  .then(result => {
    if(result) {
      console.log(`Successfully found document: ${result}.`);
    } else {
      console.log("No document matches the provided query.");
    }
    return result;
  })
  .catch(err => console.error(`Failed to find document: ${err}`));

To call the collection.findOne() action from a JavaScript SDK, use the RemoteMongoCollection.findOne() method.

const query = { "quantity": { "$gte": 25 } };
const options = {
  "projection": {
    "title": 1,
    "quantity": 1,
  },
  "sort": { "title": -1 },
};
itemsCollection.findOne(query, options)
  .then((result) => {
    if (result) {
      console.log(`Successfully found document: ${result}.`);
    } else {
      console.log('No document matches the provided query.');
    }
  })
  .catch((err) => console.error(`Failed to find document: ${err}`));

To call the collection.findOne() action from the Java/Android SDK, use the RemoteMongoCollection.findOne() method.

Document query = new Document().append("quantity",
    new Document().append("$gte", 20));

Document projection = new Document()
    .append("_id", 1)
    .append("quantity", 1);
Document sort = new Document()
    .append("quantity", -1);

RemoteFindOptions options = new RemoteFindOptions()
    .sort(sort)
    .projection(projection);

final Task <Document> findOneAndUpdateTask = itemsCollection.findOne(query, options);
findOneAndUpdateTask.addOnCompleteListener(new OnCompleteListener <Document> () {
    @Override
    public void onComplete(@NonNull Task <Document> task) {
        if (task.getResult() == null) {
            Log.d("app", String.format("No document matches the provided query"));
        }
        else if (task.isSuccessful()) {
            Log.d("app", String.format("Successfully found document: %s",
                task.getResult()));
        } else {
            Log.e("app", "Failed to findOne: ", task.getException());
        }
    }
});
let query: Document = ["quantity": [ "$gte": 20 ] as Document]
let sort: Document = ["quantity": -1]
itemsCollection?.findOne(query, options: RemoteFindOptions.init(sort: sort)) { doc in
    switch doc {
    case .success(let doc):
        switch doc {
        case .none:
            print("No document matches the provided query")
        case .some(let doc):
            print("Successfully found document: \(doc)")
        }
    case .failure(let err):
        print("Failed to findOne: \(err)")
    }

Parameters

The collection.findOne() action has the following form:

findOne(query, projection)
Parameter Description

Query Filter

query: <document>

Optional. A standard MongoDB query document that specifies which documents to find. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

Specify an empty query filter ({}) or omit this parameter to return the first document in the collection.

Projection

projection: <document>

Optional. A document that specifies which fields MongoDB should return or withhold from a returned document.

To return all fields in the document, omit this parameter or specify an empty projection document ({}).

To return specific fields and the document’s _id, specify the fields in the projection document with a value of 1:

// Includes the field in returned documents
{ <Field Name>: 1 }

To withhold specific fields, specify the fields in the projection document with a value of 0:

// Withholds the field from returned documents
{ <Field Name>: 0 }

Note

You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field:

// Invalid
// Can't simultaneously include and withhold
{ "name": 1, "address": 0 }

The exception to this rule is the _id field, which you may withhold from any query:

// Valid
// Can exclude _id while including other fields
{ "_id": 0, "name": 1 }

The findOne() method has the following form:

findOne(query, options)
Parameter Description

Query Filter

query: <document>

Optional. A standard MongoDB query document that specifies which documents to find. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

Specify an empty query filter ({}) or omit this parameter to return the first document in the collection.

Query Options

options: <document>

“”

A document that specifies configuration options for the query. The options document has the following form:

{
   "projection": <document>,
   "sort": <document>
}

Projection

options.projection: <document>

Optional. A document that specifies which fields MongoDB should return or withhold in the returned document.

To return all fields in the document, omit this parameter or specify an empty projection document ({}).

To return specific fields and the document’s _id, specify the fields in the projection document with a value of 1:

// Includes the field in returned documents
{ <Field Name>: 1 }

To withhold specific fields, specify the fields in the projection document with a value of 0:

// Withholds the field from returned documents
{ <Field Name>: 0 }

Note

You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field:

// Invalid
// Can't simultaneously include and withhold
{ "name": 1, "address": 0 }

The exception to this rule is the _id field, which you may withhold from any query:

// Valid
// Can exclude _id while including other fields
{ "_id": 0, "name": 1 }

Sort

options.sort: <document>

Optional. A document that specifies a sort order for the query result set. Sort documents specify one or more fields to sort on. The value of each field indicates whether MongoDB should sort it in ascending (1) or descending (-1) order. For more information, see cursor.sort.

Example

The following sort document specifies that documents should be sorted first by age from highest to lowest. Once sorted by age, the result set should further be sorted by name in alphabetical order for each distinct age value.

{ age: -1, name: 1 }

The findOne() method has the following form:

findOne​(Bson filter, RemoteFindOptions options, Class<ResultT> resultClass)
Parameter Description

Query Filter

filter: <document>

Required. A standard MongoDB query document that specifies which document to find. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

If multiple documents match the query, only the first document in sort order or natural order will be updated.

Find Options

options: <RemoteFindOptions>

Optional: An instance of the RemoteFindOptions. class.

RemoteFindOptions options = new RemoteFindOptions()
    .sort(sort)
    .projection(projection);

Sort

RemoteFindOneOptions.sort: <document>

Optional. Specifies the query sort order. Sort documents specify one or more fields to sort on where the value of each field indicates whether MongoDB should sort it in ascending (1) or descending (-1) order. The sort order determines which document collection.findOne() returns.

Example

The following sort document specifies that documents should be sorted first by age from highest to lowest. Once sorted by age, the result set should further be sorted by name in alphabetical order for each distinct age value.

Document sort = new Document()
 .append("age", -1)
 .append("name", 1);

Projection

RemoteFindOneOptions.projection: <document>

Optional. A document that specifies which fields MongoDB should return or withhold in the document returned by the query.

To return all fields in the matching document, omit this parameter or specify an empty projection document (new Document()).

To return specific fields and the document’s _id, specify the fields in the projection document with a value of 1:

// Includes the field in returned document
Document sort = new Document()
  .append(<Field Name>, 1);

To withhold specific fields, specify the fields in the projection document with a value of 0:

// Withholds the field from returned document
Document sort = new Document()
  .append(<Field Name>, 0);

Note

You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field:

// Invalid
// Can't simultaneously include and withhold
Document sort = new Document()
 .append("name", 1)
 .append("address", 0);

The exception to this rule is the _id field, which you may withhold from any query:

// Valid
// Can exclude _id while including other fields
Document sort = new Document()
 .append("_id", 0)
 .append("name", 1);

Limit

RemoteFindOptions.limit: <int>
Optional. The findOne method ignores this value completely.

Result Class

resultClass: <class>
Optional. Indicates the type of the document returned by the operation.
public func findOne(_ filter: Document = [:],
        options: RemoteFindOptions? = nil,
        _ completionHandler: @escaping (StitchResult<CollectionType?>) -> Void)
Parameter Description

Query Filter

filter: <document>

Optional. Default [:] A standard MongoDB query document that specifies which document to update. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

If multiple documents match the query, only the first document in sort order or natural order will be updated.

Find Options

options: <RemoteFindOptions>

Optional: A RemoteFindOptions struct that can be initialized with the following values.

RemoteFindOptions.init(
    "limit": <Int64>,
    "projection": <document>,
    "sort": <document>,
)

Limit

RemoteFindOptions.limit: <Int64>
Optional. The maximum number of documents to include in the query result set. If the result set contains more documents than the specified limit, the query will return documents in order up to the limit not to exceed 50,000 documents.

Projection

RemoteFindOptions.projection: <document>

Optional. A document that specifies which fields MongoDB should return or withhold in the returned document.

To return all fields in the document, omit this parameter.

To return specific fields and the document’s _id, specify the fields in the projection document with a value of 1:

// Includes the field in returned documents
[ <Field Name>: 1 ]

To withhold specific fields, specify the fields in the projection document with a value of 0:

// Withholds the field from returned documents
[ <Field Name>: 0 ]

Note

You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field:

// Invalid
// Can't simultaneously include and withhold
[ "name": 1, "address": 0 ]

The exception to this rule is the _id field, which you may withhold from any query:

// Valid
// Can exclude _id while including other fields
[ "_id": 0, "name": 1 ]

Sort

RemoteFindOptions.sort: <document>

Optional. Specifies the query sort order. Sort documents specify one or more fields to sort on where the value of each field indicates whether MongoDB should sort it in ascending (1) or descending (-1) order. The sort order determines which document collection.findOneAndUpdate() affects.

Example

The following sort document specifies that documents should be sorted first by age from highest to lowest. Once sorted by age, the result set should further be sorted by name in alphabetical order for each distinct age value.

[ "age": -1, "name": 1 ]

completionHandler

(StitchResult<CollectionType?>) -> Void

Required. A completion handler that accepts StitchResult optional.

This should be matched to check for successful completion of the operation.

Return Value

The collection.findOne() action returns a Promise that resolves to the first document in the collection that matches the query filter. If no documents match the specified query, the promise resolves to null.

Promise<document|null>

The collection.findOne() action returns a Promise that resolves to the first document in the collection that matches the query filter. If no documents match the specified query, the promise resolves to null.

Promise<document|null>

The findOne() function returns a Task containing the matched document, which can be accessed using the task.getResult() method. The type of the result contained within the Task varies based on the configuration of the RemoteMongoCollection used for the operation and the value of the resultClass parameter.

  • If resultClass is specified, the returned Task contains an object of type ResultT, which resolves to type resultClass.
  • If a resultClass is not specified, the returned Task contains an object of type DocumentT, which resolves to type Document unless otherwise specified when the RemoteMongoCollection was instantiated.
  • If no document matches the provided query, the task will fail and details can be accessed using task.getException(). If no
Task<ResultT result | DocumentT result>

The findOne method will call the supplied completionHandler with a StitchResult