Query MongoDB - Swift SDK
On this page
- Overview
- Use Cases
- Prerequisites
- Example Data
- Async/Await Query MongoDB
- Create Documents
- Insert a Single Document
- Insert Multiple Documents
- Read Documents
- Find a Single Document
- Find Multiple Documents
- Find and Sort Documents
- Count Documents in the Collection
- Update Documents
- Update a Single Document
- Update Multiple Documents
- Upsert Documents
- Delete Documents
- Delete a Single Document
- Delete Multiple Documents
- Watch for Changes
- Watch for Changes in a Collection
- Watch for Changes in a Collection to Specific IDs
- Watch for Changes in a Collection with a Filter
- Watch a Collection as an Async Sequence
- Aggregate Documents
- Filter Documents
- Group Documents
- Project Document Fields
- Add Fields to Documents
- Unwind Array Values
Overview
You can query data stored in MongoDB directly from your client application code by using the Realm Swift SDK's MongoClient with the Query API. Atlas App Services provides data access rules on collections to securely retrieve results based on the logged-in user or the content of each document.
Tip
See also:
This page covers querying a MongoDB data source directly. To filter data you retrieve from a realm, see: Filter Data.
Use Cases
There are a variety of reasons you might want to query a MongoDB data source. Working with data in your client via Atlas Device Sync is not always practical or possible. You might want to query MongoDB when:
The data set is large or the client device has constraints against loading the entire data set
You are retrieving documents that are not modeled in Realm
Your app needs to access collections that don't have strict schemas
A non-Realm service generates collections that you want to access
While not exhaustive, these are some common use cases for querying MongoDB directly.
Prerequisites
Before you can query MongoDB from your client application, you must set up MongoDB Data Access in your App Services App. To learn how to set up your backend App to let the Realm SDK query Atlas, refer to Set Up MongoDB Data Access in the App Services documentation.
Example Data
These examples operate on a MongoDB collection that describes coffee drinks in a chain of coffee shops. The documents represent objects with these properties:
class CoffeeDrink: Object { true) var _id: ObjectId (primaryKey: var name: String var beanRegion: String? var containsDairy: Bool var storeNumber: Int }
The complete code for each example includes logging in and instantiating a MongoDB collection handle before completing each operation. For brevity, these examples omit the login and collection handle code. However, each complete example looks like this:
appClient.login(credentials: Credentials.anonymous) { (result) in // Remember to dispatch back to the main thread in completion handlers // if you want to do anything on the UI. DispatchQueue.main.async { switch result { case .failure(let error): print("Login failed: \(error)") case .success(let user): print("Login as \(user) succeeded!") // mongodb-atlas is the cluster service name let mongoClient = user.mongoClient("mongodb-atlas") // Select the database let database = mongoClient.database(named: "ios") // Select the collection let collection = database.collection(withName: "CoffeeDrinks") // This document represents a CoffeeDrink object let drink: Document = [ "name": "Colombian Blend", "beanRegion": "Timbio, Colombia", "containsDairy": false, "storeNumber": 43] // Insert the document into the collection collection.insertOne(drink) { result in switch result { case .failure(let error): print("Call to MongoDB failed: \(error.localizedDescription)") return case .success(let objectId): // Success returns the objectId for the inserted document print("Successfully inserted a document with id: \(objectId)") } } } } }
Async/Await Query MongoDB
New in version 10.16.0.
The Realm Swift SDK provides async/await versions of the MongoCollection methods.
All of the methods on this page are compatible with the async/await syntax.
This example illustrates that syntax for the collection.insertOne()
method.
You can see the completion handler version in Insert a Single Document.
// This document represents a CoffeeDrink object let drink: Document = [ "name": "Bean of the Day", "beanRegion": "Timbio, Colombia", "containsDairy": false, "storeNumber": 43] do { // Use the async collection method to insert the document let objectId = try await collection.insertOne(drink) print("Successfully inserted a document with id: \(objectId)") } catch { print("Call to MongoDB failed: \(error.localizedDescription)") }
Starting with Realm Swift SDK Versions 10.15.0 and 10.16.0, many of the Realm APIs support the Swift async/await syntax. Projects must meet these requirements:
Swift SDK Version | Swift Version Requirement | Supported OS |
---|---|---|
10.25.0 | Swift 5.6 | iOS 13.x |
10.15.0 or 10.16.0 | Swift 5.5 | iOS 15.x |
If your app accesses Realm in an async/await
context, mark the code
with @MainActor
to avoid threading-related crashes.
Create Documents
These code snippets demonstrate how to insert one or more documents into a MongoDB collection from a mobile application. These methods take one or more documents and return a result. Success returns the objectId of the inserted document, or an array of objectIds in order when inserting multiple documents.
Insert a Single Document
You can insert a single document using collection.insertOne().
This snippet inserts a single document describing a "Colombian Blend" coffee drink into a collection of documents that describe coffee drinks for sale in a group of stores:
// This document represents a CoffeeDrink object let drink: Document = [ "name": "Colombian Blend", "beanRegion": "Timbio, Colombia", "containsDairy": false, "storeNumber": 43] // Insert the document into the collection collection.insertOne(drink) { result in switch result { case .failure(let error): print("Call to MongoDB failed: \(error.localizedDescription)") return case .success(let objectId): // Success returns the objectId for the inserted document print("Successfully inserted a document with id: \(objectId)") } }
Insert Multiple Documents
You can insert multiple documents using collection.insertMany().
This snippet inserts three documents describing coffee drinks into a collection of documents that describe coffee drinks for sale in a group of stores:
let drink: Document = [ "name": "Bean of the Day", "beanRegion": "Timbio, Colombia", "containsDairy": false, "storeNumber": 42] let drink2: Document = [ "name": "Maple Latte", "beanRegion": "Yirgacheffe, Ethiopia", "containsDairy": true, "storeNumber": 42] let drink3: Document = [ "name": "Bean of the Day", "beanRegion": "San Marcos, Guatemala", "containsDairy": false, "storeNumber": 47] // Insert the documents into the collection collection.insertMany([drink, drink2, drink3]) { result in switch result { case .failure(let error): print("Call to MongoDB failed: \(error.localizedDescription)") return case .success(let objectIds): print("Successfully inserted \(objectIds.count) new documents.") } }
Read Documents
These code snippets demonstrate how to read data stored in a MongoDB collection
from a mobile application. Read operations use a standard query syntax to specify which documents to return
from the database. Read operations return a result that that resolves to
either a single matched document (in the case of findOneDocument()
), a
long
numeric value (in the case of count()
) or an array of matched
documents (in the case of find()
).
Find a Single Document
You can find a single document using collection.findOneDocument().
This snippet finds a single document from a collection of documents
that describe coffee drinks for sale in a
group of stores, where the document's name
field contains the string
value "Colombian Blend":
let queryFilter: Document = ["name": "Colombian Blend"] collection.findOneDocument(filter: queryFilter) { result in switch result { case .failure(let error): print("Did not find matching documents: \(error.localizedDescription)") return case .success(let document): print("Found a matching document: \(String(describing: document))") } }
Find Multiple Documents
You can find multiple documents using collection.find().
This snippet finds all documents in a collection of documents that
describe coffee drinks for sale in a group
of stores, where the document's name
field contains the value "Americano":
let queryFilter: Document = ["name": "Americano"] collection.find(filter: queryFilter) { result in switch result { case .failure(let error): print("Call to MongoDB failed: \(error.localizedDescription)") return case .success(let bsonDocumentArray): print("Results: ") for bsonDocument in bsonDocumentArray { print("Coffee drink named: \(String(describing: bsonDocument["name"]))") } } }
Find and Sort Documents
You can sort documents in a collection by initializing an instance of
FindOptions
with your preferred sort options. FindOptions
has three parameters:
limit,
projection,
and sorting.
The sorting
argument can be an array of key-value pairs where each key
represents a field. For each key, the value 1
sorts in descending order,
or -1
sorts in ascending order.
You then pass the FindOptions
instance to the collection.find()
method
when running the query.
This snippet finds all documents in a collection of documents that
describe coffee drinks for sale in a group
of stores, where the document's name
field contains the value "Americano",
sorted in descending order by the beanRegion
field:
let queryFilter: Document = ["name": "Americano"] let findOptions = FindOptions(0, nil, [["beanRegion": 1]]) collection.find(filter: queryFilter, options: findOptions) { result in switch result { case .failure(let error): print("Call to MongoDB failed: \(error.localizedDescription)") return case .success(let documents): print("Results: ") for document in documents { print("Coffee drink: \(document)") } } }
Count Documents in the Collection
You can count documents in a collection using collection.count(). You can specify an optional query and limit to determine which documents to count. If you don't specify a query, the action counts all documents in the collection.
This snippet counts the number of documents in a collection of documents
that describe coffee drinks for sale in a
group of stores, where the document's name
field contains the value
"Bean of the Day":
let queryFilter: Document = ["name": "Bean of the Day"] collection.count(filter: queryFilter) { result in switch result { case .failure(let error): print("Call to MongoDB failed: \(error.localizedDescription)") return case .success(let count): print("Found this many documents in the collection matching the filter: \(count)") } }
Update Documents
These code snippets demonstrate how to update data stored in a MongoDB
collection from a mobile application. Update operations use queries to
specify which documents to update, and update operators to desribe how to mutate documents that match
the query. Update operations return a result that resolves to an
UpdateResult
or Error
.
Update a Single Document
You can update a single document using collection.updateOneDocument().
This snippet updates a single document in a collection of documents
that describe coffee drinks for sale in a
group of stores. This update operation queries for a document whose
name
field contains the value "Bean of the Day", and sets the
containsDairy
field to true
:
let queryFilter: Document = ["name": "Bean of the Day", "storeNumber": 42] let documentUpdate: Document = ["$set": ["containsDairy": true]] collection.updateOneDocument(filter: queryFilter, update: documentUpdate) { result in switch result { case .failure(let error): print("Failed to update document: \(error.localizedDescription)") return case .success(let updateResult): if updateResult.matchedCount == 1 && updateResult.modifiedCount == 1 { print("Successfully updated a matching document.") } else { print("Did not update a document") } }
Update Multiple Documents
You can update multiple documents using collection.updateManyDocuments().
This snippet updates multiple documents in a collection of documents
that describe coffee drinks for sale in a
group of stores. This update operation queries for documents where the
name
field contains the value "Bean of the Day", and changes the
containsDairy
field to true
:
let queryFilter: Document = ["name": "Bean of the Day"] let documentUpdate: Document = ["$set": ["containsDairy": true]] collection.updateManyDocuments(filter: queryFilter, update: documentUpdate) { result in switch result { case .failure(let error): print("Failed to update document: \(error.localizedDescription)") return case .success(let updateResult): print("Successfully updated \(updateResult.modifiedCount) documents.") } }
Upsert Documents
If an update operation does not match any document in the collection,
you can automatically insert a single new document into the collection
that matches the update query by setting the upsert
option to
true
.
The following snippet updates a document in a collection of documents
that describe coffee drinks for sale in a
group of stores. If no document matches the query, it inserts a new
document if no document. This operation queries for documents
where the name
field has a value of "Bean of the Day", and
the storeNumber
field has a value of 55
.
Because this snippet sets the upsert
option to true
, if no
document matches the query, MongoDB creates a new document that includes
both the query and specified updates:
let queryFilter: Document = ["name": "Bean of the Day", "storeNumber": 55] let documentUpdate: Document = ["name": "Bean of the Day", "beanRegion": "Yirgacheffe, Ethiopia", "containsDairy": false, "storeNumber": 55] collection.updateOneDocument(filter: queryFilter, update: documentUpdate, upsert: true) { result in switch result { case .failure(let error): print("Failed to update document: \(error.localizedDescription)") return case .success(let updateResult): if let unwrappedDocumentId = updateResult.documentId { print("Successfully upserted a document with id: \(unwrappedDocumentId)") } else { print("Did not upsert a document") } } }
Delete Documents
These code snippets demonstrate how to delete documents that
are stored in a MongoDB collection from a mobile application.
Delete operations use a query to specify which documents to delete
and return results that resolve to an Int
count of deleted documents
or Error
.
Delete a Single Document
You can delete a single document from a collection using collection.deleteOneDocument().
This snippet deletes one document in a collection of documents
that describe coffee drinks for sale in a
group of stores. This operation queries for a document where the name
field has a value of "Mocha" and the storeNumber
field has a value of
17
, and deletes it.
let queryFilter: Document = ["name": "Mocha", "storeNumber": 17] collection.deleteOneDocument(filter: queryFilter) { deletedResult in switch deletedResult { case .failure(let error): print("Failed to delete a document: \(error.localizedDescription)") return case .success(let deletedResult): print("Successfully deleted a document.") } }
Delete Multiple Documents
You can delete multiple items from a collection using collection.deleteManyDocuments().
This snippet deletes all documents in a collection of documents
that describe coffee drinks for sale in a
group of stores that match the query for documents whose name
field
contains the value "Caramel Latte":
let filter: Document = ["name": "Caramel Latte"] collection.deleteManyDocuments(filter: filter) { deletedResult in switch deletedResult { case .failure(let error): print("Failed to delete a document: \(error.localizedDescription)") return case .success(let deletedResult): print("Successfully deleted \(deletedResult) documents.") } }
Watch for Changes
You can watch a collection for change notifications that MongoDB emits whenever a document in the collection is created, modified, or deleted. Each notification specifies a document that changed, how it changed, and the full document after the operation that caused the event.
Important
Serverless Limitations
You cannot watch for changes if the data source is an Atlas serverless instance. MongoDB serverless currently does not support change streams, which are used on watched collections to listen for changes.
Watch for Changes in a Collection
You can open a stream of changes made to a collection by calling collection.watch(). This function creates a publisher that emits a AnyBSON change event when the MongoDB collection changes.
You can optionally watch a filtered list of _ids
in the collection with
collection.watch(filterIds:),
or apply a $match
filter to incoming change events with collection.watch(matchFilter:).
The .watch()
method can take a ChangeEventDelegate to subscribe to changes on a stream.
For example, with this ChangeEventDelegate
:
class MyChangeStreamDelegate: ChangeEventDelegate { func changeStreamDidOpen(_ changeStream: RealmSwift.ChangeStream) { print("Change stream opened: \(changeStream)") } func changeStreamDidClose(with error: Error?) { if let anError = error { print("Change stream closed with error: \(anError.localizedDescription)") } else { print("Change stream closed") } } func changeStreamDidReceive(error: Error) { print("Received error: \(error.localizedDescription)") } func changeStreamDidReceive(changeEvent: RealmSwift.AnyBSON?) { guard let changeEvent = changeEvent else { return } guard let document = changeEvent.documentValue else { return } print("Change event document received: \(document)") } }
This code watches for changes to documents in the CoffeeDrinks
collection:
appClient.login(credentials: Credentials.anonymous) { (result) in DispatchQueue.main.async { switch result { case .failure(let error): print("Login failed: \(error)") case .success(let user): print("Login as \(user) succeeded!") // Continue below } // Set up the client, database, and collection. let client = self.appClient.currentUser!.mongoClient("mongodb-atlas") let database = client.database(named: "ios") let collection = database.collection(withName: "CoffeeDrinks") // Watch the collection. In this example, we use a queue and delegate, // both of which are optional arguments. let queue = DispatchQueue(label: "io.realm.watchQueue") let delegate = MyChangeStreamDelegate() let changeStream = collection.watch(delegate: delegate, queue: queue) // Adding a document triggers a change event. let drink: Document = [ "name": "Bean of the Day", "beanRegion": "Timbio, Colombia", "containsDairy": false, "storeNumber": 42] collection.insertOne(drink) { result in switch result { case .failure(let error): print("Call to MongoDB failed: \(error.localizedDescription)") return case .success(let objectId): print("Successfully inserted a document with id: \(objectId)") } } // After you're done watching for events, close the change stream. changeStream.close() } }
Watch for Changes in a Collection to Specific IDs
You can watch for changes in a collection to a specific list of objects by
passing in their _id
. Call collection.watch(filterIds: )
with an array of ObjectIds to receive only change events that apply to those
documents.
Consider an example that uses this ChangeEventDelegate:
class MyChangeStreamDelegate: ChangeEventDelegate { func changeStreamDidOpen(_ changeStream: RealmSwift.ChangeStream) { print("Change stream opened: \(changeStream)") } func changeStreamDidClose(with error: Error?) { if let anError = error { print("Change stream closed with error: \(anError.localizedDescription)") } else { print("Change stream closed") } } func changeStreamDidReceive(error: Error) { print("Received error: \(error.localizedDescription)") } func changeStreamDidReceive(changeEvent: RealmSwift.AnyBSON?) { guard let changeEvent = changeEvent else { return } guard let document = changeEvent.documentValue else { return } print("Change event document received: \(document)") } }
The code below uses this delegate to watch for changes to specific
documents in the CoffeeDrinks
collection:
appClient.login(credentials: Credentials.anonymous) { (result) in DispatchQueue.main.async { switch result { case .failure(let error): print("Login failed: \(error)") case .success(let user): print("Login as \(user) succeeded!") // Continue below } // Set up the client, database, and collection. let client = self.appClient.currentUser!.mongoClient("mongodb-atlas") let database = client.database(named: "ios") let collection = database.collection(withName: "CoffeeDrinks") // Watch the collection. In this example, we use a queue and delegate, // both of which are optional arguments. // `filterIds` is an array of specific document ObjectIds you want to watch. let queue = DispatchQueue(label: "io.realm.watchQueue") let delegate = MyChangeStreamDelegate() let changeStream = collection.watch(filterIds: [drinkObjectId], delegate: delegate, queue: queue) // An update to a relevant document triggers a change event. let queryFilter: Document = ["_id": AnyBSON(drinkObjectId) ] let documentUpdate: Document = ["$set": ["containsDairy": true]] collection.updateOneDocument(filter: queryFilter, update: documentUpdate) { result in switch result { case .failure(let error): print("Call to MongoDB failed: \(error.localizedDescription)") return case .success(let updateResult): print("Successfully updated the document") } } // After you're done watching for events, close the change stream. changeStream.close() } }
Watch for Changes in a Collection with a Filter
You can open a stream of changes made to documents in a collection that
fulfill certain criteria by calling collection.watch(matchFilter: ).
This method accepts a Document
parameter that is
used as the query of a $match operator to process each
database event that occurs while watching the
collection.
Consider an example that uses this ChangeEventDelegate:
class MyChangeStreamDelegate: ChangeEventDelegate { func changeStreamDidOpen(_ changeStream: RealmSwift.ChangeStream) { print("Change stream opened: \(changeStream)") } func changeStreamDidClose(with error: Error?) { if let anError = error { print("Change stream closed with error: \(anError.localizedDescription)") } else { print("Change stream closed") } } func changeStreamDidReceive(error: Error) { print("Received error: \(error.localizedDescription)") } func changeStreamDidReceive(changeEvent: RealmSwift.AnyBSON?) { guard let changeEvent = changeEvent else { return } guard let document = changeEvent.documentValue else { return } print("Change event document received: \(document)") } }
The code below uses this delegate to watch for changes to documents in the
CoffeeDrink
collection. It only triggers the provided callback for
events whose documents have a storeNumber
value of 42
:
appClient.login(credentials: Credentials.anonymous) { (result) in DispatchQueue.main.async { switch result { case .failure(let error): print("Login failed: \(error)") case .success(let user): print("Login as \(user) succeeded!") // Continue below } // Set up the client, database, and collection. let client = self.appClient.currentUser!.mongoClient("mongodb-atlas") let database = client.database(named: "ios") let collection = database.collection(withName: "CoffeeDrinks") // Watch the collection. In this example, we use a queue and delegate, // both of which are optional arguments. let queue = DispatchQueue(label: "io.realm.watchQueue") let delegate = MyChangeStreamDelegate() let matchFilter = [ "fullDocument.storeNumber": AnyBSON(42) ] let changeStream = collection.watch(matchFilter: matchFilter, delegate: delegate, queue: queue) // An update to a relevant document triggers a change event. let queryFilter: Document = ["_id": AnyBSON(drinkObjectId) ] let documentUpdate: Document = ["$set": ["containsDairy": true]] collection.updateOneDocument(filter: queryFilter, update: documentUpdate) { result in switch result { case .failure(let error): print("Call to MongoDB failed: \(error.localizedDescription)") return case .success(let updateResult): print("Successfully updated the document") } } // After you're done watching for events, close the change stream. changeStream.close() } }
Watch a Collection as an Async Sequence
New in version 10.37.0.
You can open an async sequence to watch for changes to a collection. In an async context, call changeEvents() on a collection to open a change stream. This provides an async sequence of AnyBSON values containing information about each change to the MongoDB collection.
You can optionally provide a changeEvents(onOpen: ) callback which is invoked when the watch stream has initialized on the server.
The changeEvents()
API can take filterIds
or a matchFilter
to watch a subset of documents in a collection, similar to the examples above.
The following snippet watches for changes to any documents in the
CoffeeDrinks
collection as an async sequence:
let user = try await appClient.login(credentials: Credentials.anonymous) // Set up the client, database, and collection. let mongoClient = user.mongoClient("mongodb-atlas") let database = mongoClient.database(named: "ios") let collection = database.collection(withName: "CoffeeDrinks") // Set up a task you'll later await to keep the change stream open, // and you can cancel it when you're done watching for events. let task = Task { // Open the change stream. let changeEvents = collection.changeEvents(onOpen: { print("Successfully opened change stream") }) // Await events in the change stream. for try await event in changeEvents { let doc = event.documentValue! print("Received event: \(event.documentValue!)") } } // Updating a document in the collection triggers a change event. let queryFilter: Document = ["_id": AnyBSON(objectId) ] let documentUpdate: Document = ["$set": ["containsDairy": true]] let updateResult = try await collection.updateOneDocument(filter: queryFilter, update: documentUpdate) // Cancel the task when you're done watching the stream. task.cancel() _ = await task.result
Aggregate Documents
Aggregation operations run all documents in a collection through a series of data aggregation stages called an aggregation pipeline. Aggregation allows you to filter and transform documents, collect summary data about groups of related documents, and other complex data operations.
You can configure and run aggregation operations on a collection using collection.aggregate().
An aggregation operation accepts a list of aggregation stages as input
and returns a result that resolves to a collection of documents processed
by the pipeline, or an Error
.
Filter Documents
You can use the $match stage to filter documents using standard MongoDB query syntax:
This $match
stage filters documents to include only those where the
storeNumber
field has a value equal to 42
:
let pipeline: [Document] = [["$match": ["storeNumber": ["$eq": 42]]]] collection.aggregate(pipeline: pipeline) { result in switch result { case .failure(let error): print("Failed to aggregate: \(error.localizedDescription)") return case .success(let documents): print("Successfully ran the aggregation:") for document in documents { print("Coffee drink: \(document)") } } }
Group Documents
You can use the $group stage to aggregate summary
data for one or more documents. MongoDB groups documents based
on the expression defined in the _id
field of the $group
stage.
You can reference a specific document field by prefixing the field name
with a $
.
This $group
stage arranges documents by the value of their
storeNumber
field. It then calculates the number of coffee drink
documents that contain that store number in the field's value. In other
words, we're calculating the number of coffee drinks for each store number.
let pipeline: [Document] = [["$group": ["_id": "$storeNumber", "numItems": ["$sum": 1]]]] collection.aggregate(pipeline: pipeline) { result in switch result { case .failure(let error): print("Failed to aggregate: \(error.localizedDescription)") return case .success(let results): print("Successfully ran the aggregation.") for result in results { print(result) } } }
Project Document Fields
You can use the $project stage to include or omit specific fields from documents or to calculate new fields using aggregation operators. Projections work in two ways:
Specify that you want to include fields by using a
1
. This has the side-effect of implicitly excluding all unspecified fields.Specify that you want to exclude fields by using a
0
. This has the side-effect of implicitly including all unspecified fields.
These two methods of projection are mutually exclusive. If you specify fields to include, you cannot also specify fields to exclude, and vice versa.
Note
The _id
field is a special case: it is always included in every
query unless explicitly specified otherwise. For this reason, you
can exclude the _id
field with a 0
value while simultaneously
including other fields, like storeNumber
, with a 1
. Only the
special case of exclusion of the _id
field allows both exclusion
and inclusion in one $project
stage.
For this example, assume the CoffeeDrink
document has a store
field that is a string value containing the word "Store" with a number,
such as "Store 42", similar to these documents:
let drink: Document = [ "name": "Bean of the Day", "beanRegion": "Timbio, Colombia", "containsDairy": false, "store": "Store 42"] let drink2: Document = [ "name": "Bean of the Day", "beanRegion": "Yirgacheffe, Ethiopia", "containsDairy": true, "store": "Store 47"]
The following $project
stage omits the _id
field, includes
the name
field, and creates a new field named storeNumber
.
The storeNumber
is generated using two aggregation operators:
$split
separates thestore
string representation into two string segments surrounding the space character. For example, the value "Store 42" split in this way returns an array with two elements: "Store" and "42".$arrayElemAt
selects a specific element from an array based on the second argument. In this case, the value1
selects the second element from the array generated by the$split
operator since arrays index from0
. For example, the value ["Store", "42"] passed to this operation would return a value of "42".
let pipeline: [Document] = [["$project": ["_id": 0, "name": 1, "storeNumber": ["$arrayElemAt": [["$split": ["$store", " "]], 1]]]]] collection.aggregate(pipeline: pipeline) { result in switch result { case .failure(let error): print("Failed to aggregate: \(error.localizedDescription)") return case .success(let results): print("Successfully ran the aggregation.") for result in results { print(result) } } }
Add Fields to Documents
You can use the $addFields stage to add new fields with calculated values using aggregation operators.
Note
$addFields
is similar to $project but does not allow you to
include or omit fields.
For this example, assume the CoffeeDrink
document has a store
field that is a string value containing the word "Store" with a number,
such as "Store 42", similar to these documents:
let drink: Document = [ "name": "Bean of the Day", "beanRegion": "Timbio, Colombia", "containsDairy": false, "store": "Store 42"] let drink2: Document = [ "name": "Bean of the Day", "beanRegion": "Yirgacheffe, Ethiopia", "containsDairy": true, "store": "Store 47"]
The following $addFields
stage creates a new field named
storeNumber
where the value is the output of two aggregate operators
that transform the value of the store
field.
let pipeline: [Document] = [["$addFields": ["storeNumber": ["$arrayElemAt": [["$split": ["$store", " "]], 1]]]]] collection.aggregate(pipeline: pipeline) { result in switch result { case .failure(let error): print("Failed to aggregate: \(error.localizedDescription)") return case .success(let results): print("Successfully ran the aggregation.") for result in results { print(result) } } }
Unwind Array Values
You can use the $unwind stage to transform a single document containing an array into multiple documents containing individual values from that array. When you unwind an array field, MongoDB copies each document once for each element of the array field but replaces the array value with the array element in each copy.
Consider this document that includes a featuredInPromotions
array:
let drink: Document = [ "name": "Maple Latte", "beanRegion": "Yirgacheffe, Ethiopia", "containsDairy": true, "storeNumber": 42, "featuredInPromotions": [ "Spring into Spring", "Tastes of Fall", "Winter Delights" ] ]
The following $unwind
stage creates a new document for each
element of the items
array in each document. It also adds a field
called itemIndex
to each new document that specifies the
element's position index in the original array:
let pipeline: [Document] = [["$unwind": ["path": "$featuredInPromotions", "includeArrayIndex": "itemIndex"]]] collection.aggregate(pipeline: pipeline) { result in switch result { case .failure(let error): print("Failed to aggregate: \(error.localizedDescription)") return case .success(let results): print("Successfully ran the aggregation.") for result in results { print("Coffee drink: \(result)") } } }
You could then $group
by the value of featuredInPromotions
and $sum
the number of coffee drinks in each promotion as in the group documents
example, or perform other calculations or
transformations based on your data.