Navigation

collection.find()

Definition

collection.find()

Find all documents in a collection or view that match the provided query predicates and return a handle object that allows you to access them.

Usage

Example

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

const query = { "reviews.0": { "$exists": true } };
const projection = { "_id": 0 };

return itemsCollection.find(query, projection)
  .sort({ name: 1 })
  .toArray()
  .then(items => {
    console.log(`Successfully found ${items.length} documents.`)
    items.forEach(console.log)
    return items
  })
  .catch(err => console.error(`Failed to find documents: ${err}`))

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

const query = { "reviews.0": { "$exists": true } };
const options = {
  "projection": { "_id": 0 },
  "sort": { "name": 1 }
};

itemsCollection.find(query, options).toArray()
  .then(items => {
    console.log(`Successfully found ${items.length} documents.`)
    items.forEach(console.log)
    return items
  })
  .catch(err => console.error(`Failed to find documents: ${err}`))

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

Document filterDoc = new Document()
    .append("reviews.0", new Document().append("$exists", true));

RemoteFindIterable findResults = itemsCollection
    .find(filterDoc)
    .projection(new Document().append("_id", 0))
    .sort(new Document().append("name", 1));

// One way to iterate through
findResults.forEach(item -> {
    Log.d("app", String.format("successfully found:  %s", item.toString()));
});

// Another way to iterate through
Task <List<Document>> itemsTask = findResults.into(new ArrayList<Document>());
itemsTask.addOnCompleteListener(new OnCompleteListener <List<Document>> () {
    @Override
    public void onComplete(@NonNull Task<List<Document>> task) {
        if (task.isSuccessful()) {
            List<Document> items = task.getResult();
            Log.d("app", String.format("successfully found %d documents", items.size()));
            for (Document item: items) {
                Log.d("app", String.format("successfully found:  %s", item.toString()));
            }
        } else {
            Log.e("app", "failed to find documents with: ", task.getException());
        }
    }
});

To call the collection.find() action from the Swift/iOS SDK, use the RemoteMongoCollection.find() method.

let query : Document = ["reviews.0": ["$exists": true] as Document];
let options = RemoteFindOptions(
    projection: ["_id": 0],
    sort: ["name": 1]
);

itemsCollection?.find(query, options: options).toArray({ results in
    switch results {
    case .success(let results):
        print("Successfully found \(results.count) documents: ");
        results.forEach({item in
            print(item);
        })
    case .failure(let error):
        print("Failed to find documents: \(error)");
    }
})

Parameters

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

find(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 all documents in the collection.

Projection

projection: <document>

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

To return all fields in the matching documents, 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 find() method has the following form:

find(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 all documents 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>
}

A RemoteFindOptions object, which has the following properties:

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

Projection

options.projection: <document>

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

To return all fields in the matching documents, 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.

The find() method has the following form:

find​(Bson filter, Class<ResultT> resultClass)
Parameter Description

Query Filter

filter: <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 all documents in the collection.

Result Class

resultClass: <class>
Optional. Indicates the type of the document returned by the operation.

The find() method has the following form:

find(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 all documents 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>
}

A RemoteFindOptions object, which has the following properties:

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

Projection

options.projection: <document>

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

To return all fields in the matching documents, 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.

Return Value

The collection.find() action returns a cursor object that points to any documents that match the specified query filters. You can manipulate and access documents in the query result set with the following cursor methods:

Method Description
cursor.sort(sort)

Sorts documents in the result set according to the sort filter. 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.

Note

You cannot call this method after retrieving one or more documents using cursor.next() or cursor.toArray().

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 }
cursor.limit(limit)

Specifies the maximum number of documents to include in the query result set. If the result set contains more documents than the specified limit, the cursor will return documents in order up to the limit.

Note

You cannot call this method after retrieving one or more documents using cursor.next() or cursor.toArray().

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.

Example

collection.find().next()
  .then(doc => console.log("next document", doc))
cursor.toArray()

Iterates the cursor to exhaustion and returns a Promise that resolves to an array that contains all of the iterated documents.

Example

collection.find().toArray()
  .then(docs => console.log("all documents", docs))

Note

You cannot return a cursor from a Function. Instead, evaluate the cursor using cursor.next() or cursor.toArray() and return the result.

The RemoteMongoCollection.find() method returns a RemoteMongoReadOperation object.

result: RemoteMongoReadOperation

You can access documents in the query result set by calling one of the following methods on the RemoteMongoReadOperation object:

Method Description

First Document

result.first()

“”

Return a Promise that resolves to the first document from the query result set.

See RemoteMongoReadOperation.first().

Return a StitchResult enum to the completion handler that resolves to the first document from the query result set.

See RemoteMongoReadOperation.first().

Array of Documents

result.toArray()

“”

Return a Promise that resolves to an array that contains all documents in the query result set.

See RemoteMongoReadOperation.toArray().

Return a StitchResult enum to the completion handler that resolves to an array that contains all documents in the query result set.

See RemoteMongoReadOperation.toArray().

Query Cursor

result.iterator()

“”

Return a Promise that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.next() method.

See RemoteMongoReadOperation.iterator().

Return a StitchResult enum to the completion handler that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.next() method.

See RemoteMongoReadOperation.iterator().

The RemoteMongoCollection.find() method returns a RemoteFindIterable object.

RemoteFindIterable result

You can access documents in the query result set by calling one of the following methods on the RemoteFindIterable object:

Method Description

Projection

result.projection(<document>)

Specifies which fields MongoDB should return or withhold in each document that matches the query.

To return all fields in the matching documents, 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 }

See RemoteFindIterable.projection()

Limit

result.limit(<integer>)

Limits the query result set to include no more than the specified number of documents. If the result set contains more documents than the specified limit, the query will return documents in order up to the limit.

See RemoteFindIterable.limit()

Sort

result.sort(<document>)

Sorts documents in the result set according to the sort filter. 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.

See RemoteFindIterable.sort()

Note

You cannot call this method after retrieving one or more documents using cursor.next() or cursor.toArray().

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 }

First Document

result.first()

Return a Task that resolves to the first document from the query result set.

See RemoteMongoIterable.first()

Array of Documents

result.into(<target>)

Iterate all documents in the query result set into the target object. Return a Task that resolves to the populated target object.

See RemoteMongoIterable.into()

For Each

result.forEach(<Block>)

Iterate over the result set and apply the given block to each document. Does not return a value.

See RemoteMongoIterable.forEach()

Map Document Type

result.map(<Function>)

Return a new iterator that maps each result document to a new type specified by the provided function.

See RemoteMongoIterable.map()

Query Cursor

result.iterator()

Return a Task that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.tryNext() method.

See RemoteMongoIterable.iterator()

The RemoteMongoCollection.find() method returns a StitchResult enum to its completion handler:

enum StitchResult {
  case success(result: RemoteMongoReadOperation)
  case failure(error: StitchError)
}

If the find operation was successful, the StitchResult resolves to a RemoteMongoReadOperation object that allows you to access documents in the query result set by calling one of the following methods:

Method Description

First Document

result.first()

“”

Return a Promise that resolves to the first document from the query result set.

See RemoteMongoReadOperation.first().

Return a StitchResult enum to the completion handler that resolves to the first document from the query result set.

See RemoteMongoReadOperation.first().

Array of Documents

result.toArray()

“”

Return a Promise that resolves to an array that contains all documents in the query result set.

See RemoteMongoReadOperation.toArray().

Return a StitchResult enum to the completion handler that resolves to an array that contains all documents in the query result set.

See RemoteMongoReadOperation.toArray().

Query Cursor

result.iterator()

“”

Return a Promise that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.next() method.

See RemoteMongoReadOperation.iterator().

Return a StitchResult enum to the completion handler that resolves to a RemoteMongoCursor object. You can use this cursor to iterate through each document in the query result set with the RemoteMongoCursor.next() method.

See RemoteMongoReadOperation.iterator().