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}`));

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 }

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>