Navigation

collection.find()

Definition

collection.find(query, projection)

Selects documents in a collection or view and returns a cursor to the selected documents.

Parameter Type Description
query document

Optional. Specifies a selection filter using query selectors.

Specify an empty document { } or omit this parameter to return the all documents in the collection.

projection document Optional. Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, specify an empty document { } or omit this parameter. See Projection Operators for all available projection operators.
Returns:A cursor to the documents that match the query criteria.

Behavior

Cursor Handling

A cursor cannot be returned to a client but can be manipulated and iterated inside a Stitch function. The cursor returned by collection.find() supports the following methods:

Method Description
cursor.sort(sort) Specifies that the results should be sorted. This can only be called before retrieving any documents.
cursor.limit(limit) Specifies the maximum number of results to return. This can only be called before retrieving any documents.
cursor.next() Iterates the cursor and returns a promise that resolves to the next document in the cursor. If the cursor is exhausted, the promise resolves to undefined.
cursor.toArray() Iterates the cursor to exhaustion and returns a promise that resolves to an array that contains all of the iterated documents.

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
    .find()
    .toArray()
    .then(docs => docs.map(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.

Examples

The following examples assume that the test.example namespace has been added to MongoDB in the Stitch admin console and appropriate rules have been set. See MongoDB Rules for more information.

Finding All Documents in a Collection

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

Finding Documents Matching User Input

Assume the test.example collection contains the following documents:

{ "username": "user1", comment: "abc", "_id": ObjectId("5a0c516ac7ecd33f1aea0915") }
{ "username": "user1", comment: "def", "_id": ObjectId("5a0c516ac7ecd33f1aea0916") }
{ "username": "user2", comment: "ghi", "_id": ObjectId("5a0c516ac7ecd33f1aea0917") }

MongoDB Stitch contains a function named select_comments with the following definition:

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

    return collection
      .find({"username": uname}, {"_id": 0})
      .toArray();
};

The function select_comments returns documents with the username matching the argument. The call to collection.find() also uses projection to exclude the _id field from returned documents.

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

stitchClient.executeFunction("select_comments", "user1")
    .then((documents) => {
        documents.forEach((document) => console.log(document));
    });

This outputs:

{ "username": "user1", comment: "abc" }
{ "username": "user1", comment: "def" }

Finding Documents 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.find({ "package": { "$regex": regex } }).toArray();
}

Sort and Limit Results

Assume the test.example collection contains the following documents:

{ "grade": 87, "_id": ObjectId("5a0c516ac7ecd33f1aea0915") }
{ "grade": 89, "_id": ObjectId("5a0c516ac7ecd33f1aea0916") }
{ "grade": 62, "_id": ObjectId("5a0c516ac7ecd33f1aea0917") }
{ "grade": 22, "_id": ObjectId("5a0c516ac7ecd33f1aea0918") }
{ "grade": 68, "_id": ObjectId("5a0c516ac7ecd33f1aea0919") }
{ "grade": 91, "_id": ObjectId("5a0c516ac7ecd33f1aea091A") }

MongoDB Stitch contains a function named top5 with the following definition:

exports = function() {
    const mongodb = context.services.get("mongodb-atlas");
    const collection = mongodb.db("test").collection("example");
    return collection
      .find()
      .sort({"grade": -1})
      .limit(5)
      .toArray();
};

The function top5 returns documents sorted in decreasing order by grade limited to five results. In this case, it returns the following documents:

{ "grade": 91, "_id": ObjectId("5a0c516ac7ecd33f1aea091A") }
{ "grade": 89, "_id": ObjectId("5a0c516ac7ecd33f1aea0916") }
{ "grade": 87, "_id": ObjectId("5a0c516ac7ecd33f1aea0915") }
{ "grade": 68, "_id": ObjectId("5a0c516ac7ecd33f1aea0919") }
{ "grade": 62, "_id": ObjectId("5a0c516ac7ecd33f1aea0917") }