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 options = { "limit": 1 }

return itemsCollection.findOne(query, options)
  .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 = { "limit": 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}`))

Note

The collection.findOne() action is only available in Functions and the JavaScript SDKs. You can emulate findOne behavior in the Android SDK using a collection.find() with a limit of 1:

collection.find().limit(1).first()

Note

The collection.findOne() action is only available in Functions and the JavaScript SDKs. You can emulate findOne behavior in the iOS SDK using a collection.find() with a limit of 1:

collection.find({}, [ "limit": 1 ]).first()

Parameters

The collection.findOne() action 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.

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>,
   "limit": <integer>
}

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 (0) 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: 0, name: 1 }

Limit

options.limit: <integer>
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.

Note

The collection.findOne() action is currently only available in Functions and the JavaScript SDKs.

Note

The collection.findOne() action is currently only available in Functions and the JavaScript SDKs.

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 undefined.

Promise<document|undefined>

Examples

The following examples assume that you have defined roles and permissions that allow the database operations on the test.example collection.

Finding the First Document in a Collection

exports = function() {
    const mongodb = context.services.get("mongodb-atlas");
    const collection = mongodb.db("test").collection("example");
    return collection.findOne();
};

Finding a Document Matching User Input

Assume the test.example collection contains the following documents:

{ "username": "user1", "zip": "08691", "_id": ObjectId("5a0c516ac7ecd33f1aea0915") }
{ "username": "user2", "zip": "10022", "_id": ObjectId("5a0c516ac7ecd33f1aea0916") }

Assume the Stitch app contains a function named select_zip with the following definition:

exports = function(uname) {
    const mongodb = context.services.get("mongodb-atlas");
    const collection = mongodb.db("test").collection("example");
    return collection.findOne({"username": uname}, {"_id": 0});
};

The function select_zip return a document with the username matching the argument. The call to collection.findOne() also projects to remove the _id field from the returned document.

Clients may call this function by referring to it by name. The following example calls the function from the Javascript SDK:

stitchClient.executeFunction("select_zip", "user1")
    .then((document) => console.log(document));

This outputs:

{ "username": "user1", zip: "08691" }

Finding a Document Matching a Regular Expression

Regular expressions must be encoded to BSON.

exports = function() {
  const mongodb = context.services.get("mongodb-atlas");
  const coll = mongodb.db("test").collection("example");

  const regex = BSON.BSONRegExp("com\.domain\..+", "i")
  return coll.findOne({ "package": { "$regex": regex } });
}

Working with BSON

MongoDB actions may return documents containing BSON types.

Assume the collection test.example contains the following document.

{
  "_id": ObjectId("5a0c516ac7ecd33f1aea0915"),
  "binary_data": BinData(0,"ymz="),
  "owner_id": "5b1574258f25b9240ed8f8bb"
}

When this document is retrieved in Stitch, _id is represented by a BSON.ObjectId type and binary_data is represented as a BSON.Binary type.

The following example shows how a MongoDB Stitch function can manipulate these types.

exports = function() {
  const mongodb = context.services.get("mongodb-atlas");
  const collection = mongodb.db("test").collection("example");

  return collection
    .findOne()
    .then(doc => {
      const asBase64 = doc.binary_data.toBase64();
      const asOidString = doc._id.toString();
      return { asBase64, asOidString }
    })
}

For more information on manipulating BSON in Stitch, see BSON.