Find Documents in MongoDB¶

MongoDB Logo
ServerDriversCloudToolsGuides
Get MongoDB
Close ×
MongoDB Stitch

Introduction
Tutorials
Users & Authentication
MongoDB Atlas
    Overview
    Configure MongoDB
        Link a MongoDB Atlas Cluster
        Define Roles and Permissions
        Filter Incoming Queries
        Enforce a Document Schema
        Configure Advanced Rules
        Specify Cluster Read Preference
        Enable Wire Protocol Connections
    Work With MongoDB
        Add Data to MongoDB
        Find Documents in MongoDB
        Update Documents in MongoDB
        Delete Documents from MongoDB
        Watch for Document Changes
        Run Aggregation Pipelines
        Connect Over the Wire Protocol
    Reference
        MongoDB Actions
        Query Roles
        Query Filters
        Document Schemas
        Connection Strings
        Service Limitations
        CRUD & Aggregation APIs
GraphQL
MongoDB Mobile
Functions
Triggers
External Services
Values & Secrets
Application Deployment
Hosting
Troubleshooting
Stitch Administration
Application Logs
Client SDKs
Release Notes

Stitch > MongoDB Atlas > Work With MongoDB 

Find Documents in MongoDB

On this page

Overview
    Data Model
    Snippet Setup
Methods
    Find a Single Document
    Find One or More Documents
    Count Documents in the Collection
Query Patterns
    Query Based on a Document’s ID
    Query Based on a Date
    Query Based on a Root-Level Field
    Query Based on Multiple Fields
    Query Based on an Embedded Document Field
    Query Based on an Array of Values
    Query Based on an Array Field Element
Query Operators
    Compare Values
    Evaluate a Logical Expression
    Evaluate a Regular Expression

Overview

The code snippets on this page demonstrate how to read documents that are stored in a MongoDB collection. Read operations use query filters to specify which documents to return from the database. This page also covers several different query patterns that you can use in query filters to precisely match documents.
Data Model

The examples on this page use a collection named store.items that models various items available for purchase in an online store. Each item has a name, an inventory quantity, and an array of customer reviews.

// store.items
{
_id: ,
name: ,
quantity: ,
reviews: [ { username: , comment: } ]
}

Snippet Setup

Functions JavaScript SDK Android SDK iOS SDK 

To use a code snippet in a function, you must first instantiate a MongoDB collection handle:

exports = function() {
const mongodb = context.services.get(“mongodb-atlas”);
const itemsCollection = mongodb.db(“store”).collection(“items”);
const purchasesCollection = mongodb.db(“store”).collection(“purchases”);
}

Methods
Find a Single Document

You can find a single document using the collection.findOne() action.

Note

The collection.findOne() action is currently only available in Functions. You can emulate findOne behavior in a Client SDK by calling collection.find() with a limit of 1.

The following snippet finds a single document from the items collection that has a quantity greater than or equal to 25:

Functions JavaScript SDK Android SDK iOS SDK 

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

Find One or More Documents

You can find multiple documents using the collection.find() action.

The following snippet finds all documents in the items collection that have at least one review and returns them sorted by name with the _id field omitted:

Functions JavaScript SDK Android SDK iOS SDK 

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

Count Documents in the Collection

You can count documents in a collection using the collection.count() action. You can specify a query filter to specify which documents to count. If you don’t specify a query, the action counts all documents in the collection.

The following snippet counts the number of documents in the items collection that have at least one review:

Functions JavaScript SDK Android SDK iOS SDK 

return itemsCollection.count({ “reviews.0”: { "KaTeX parse error: Expected 'EOF', got '}' at position 15: exists": true }̲ }) .then(num…{numDocs} items have a review.`))
.catch(err => console.error("Failed to count documents: ", err))

Query Patterns
Query Based on a Document’s ID

You can query a collection to find a document that has a specified ID. MongoDB automatically stores each document’s ID as an ObjectId value in the document’s _id field.

{ “_id”: }

Example

The following query matches a document in the collection that has an _id value of 5ad84b81b8b998278f773c1b:

{ “_id”: BSON.ObjectId(“5ad84b81b8b998278f773c1b”) }

Query Based on a Date

You can query a collection to find documents that have a field with a specific date value, or query for a documents within a range of dates.

{ “”: }

Example

The following query matches documents in the collection that have a createdAt date of January 23, 2019:

{ “createdAt”: new Date(“01/23/2019”) }

Example

The following query matches documents in the collection that have a createdAt date some time in the year 2019:

{
“createdAt”: {
g t e " : n e w D a t e ( " 01 / 01 / 2019 " ) , " gte": new Date("01/01/2019"), " gte":newDate("01/01/2019"),"lt”: new Date(“01/01/2020”)
}
}

Query Based on a Root-Level Field

You can query a collection based on the value of a root-level field in each document. You can specify either a specific value or a nested expression that MongoDB evaluates for each document.

For more information, see the Query Documents tutorial in the MongoDB Server Manual.

{ “”: }

Example

The following query matches documents where the name field has a value of Basketball:

{ “name”: “Basketball” }

Query Based on Multiple Fields

You can specify multiple query conditions in a single query document. Each root-level field of a query document maps to a field in the collection. MongoDB only returns documents that fulfill all query conditions.

For more information, see the Query on Embedded/Nested Documents tutorial in the MongoDB Server Manual.

{
”: ,
”:
}

Example

The following query matches documents where the name field has a value of Basketball and the quantity value is greater than zero:

{
“name”: “Basketball”,
“quantity”: { “$gt”: 0 }
}

Query Based on an Embedded Document Field

You can query a collection based on the value of embedded document fields. To specify an embedded document field, use multiple nested query expressions or standard document dot notation.

For more information, see the Query on Embedded/Nested Documents tutorial in the MongoDB Server Manual.
Nested Query Expressions

{ “”: { “”: } }

Dot Notation

{ “.”: }

Example

The following query matches documents where the first review in the reviews array was left by someone with the username JoeSchmoe:

{
“reviews.0.username”: “JoeSchmoe”
}

Query Based on an Array of Values

You can query a collection based on all the elements contained in an array field.

If you query an array field for a specific array of values, MongoDB returns documents where the array field exactly matches the specified array of values. If you want MongoDB to return documents where the array field contains all elements in the specified array of values, use the $all operator.

For more information, see the Query an Array tutorial in the MongoDB Server Manual.

{ “”: [, …] }

Example

The following query matches documents where the reviews array contains exactly one element and the element matches the specified document:

{
“reviews”: [{ username: “JoeSchmoe”, comment: “This rocks!” }]
}

Example

The following query matches documents where the reviews array contains one or more elements that match all of the the specified documents:

{
“reviews”: {
“$all”: [{ username: “JoeSchmoe”, comment: “This rocks!” }]
}
}

Query Based on an Array Field Element

You can query a collection based on the value of one or more elements in an array field.

If you query an array field with a query expression that has multiple conditions, MongoDB returns documents where any combination of the array’s elements satisfy the expression. If you want MongoDB to return documents where a single array element satisfies all of the expression conditions, use the $elemMatch operator.

For more information, see the Query an Array tutorial in the MongoDB Server Manual.

{ “”: }

Example

The following query matches documents where both conditions in the embedded expression are met by any combination of elements in the reviews array. The specified username and comment values do not need to be in the same document:

{
“reviews”: {
“username”: “JoeSchmoe”,
“comment”: “This is a great product!”
}
}

Example

The following query matches documents where both conditions in the embedded expression are met by a single element in the reviews array. The specified username and comment must be in the same document:

{
“reviews”: {
“$elemMatch”: {
“username”: “JoeSchmoe”,
“comment”: “This is a great product!”
}
}
}

Query Operators
Compare Values

You can use a comparison operator to compare the value of a document field to another value.

{ “”: { “”: } }

The following comparison operators are available:
Comparison Operator Description
$eq Matches documents where the value of a field equals a specified value.
$ne Matches documents where the value of a field does not equal a specified value.
$gt Matches documents where the value of a field is strictly greater than a specified value.
$gte Matches documents where the value of a field is greater than or equal to a specified value.
$lt Matches documents where the value of a field is strictly less than a specified value.
$lte Matches documents where the value of a field is less than or equal to a specified value.
$in Matches documents where the value of a field is included in a specified array of values.
$nin Matches documents where the value of a field is not included in a specified array of values.

Example

The following query matches documents where quantity is greater than zero and less than or equal to ten.

{
“quantity”: { “ g t " : 0 , " gt": 0, " gt":0,"lte”: 10 }
}

Evaluate a Logical Expression

You can use a logical operator to evaluate multiple expressions for a single field.

{
“”: {
“”: [, …]
}
}

The following logical operators are available:
Logical Operator Description
$and Matches documents where the value of a field matches all of the specified expressions.
$or Matches documents where the value of a field matches any of the specified expressions.
$nor Matches documents where the value of a field matches none of the specified expressions.
$not Inverts the boolean result of the specified logical expression.

Example

The following query matches documents where either quantity is greater than zero or there are no more than five documents in the reviews array.

{
KaTeX parse error: Expected '}', got 'EOF' at end of input: …"quantity": { "gt”: 0 } },
{ “reviews”: { “KaTeX parse error: Expected '}', got 'EOF' at end of input: size": { "lte”: 5 } } }
]
}

Evaluate a Regular Expression

You can use the $regex query operator to return documents with fields that match a regular expression. To avoid ambiguity with the $regex EJSON type, you must use a BSON.BSONRegExp object.

{
“”: {
“$regex”: BSON.BSONRegExp(, )
}
}

Example

The following query matches documents where the name value contains the substring ball (case-insensitive).

{
“name”: { “$regex”: BSON.BSONRegExp(".+ball", “i”) }
}

← Add Data to MongoDB Update Documents in MongoDB →

© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.
Was this page helpful?
Yes
No

你可能感兴趣的:(mongodb)