Server side swift - aggregation example?


I’ve been building some internal tools using MongoSwiftSync and I need to run some aggregations. I was looking for an example of how to configure this in Swift, but haven’t been able to find anything. It appears that aggregations are only supported in async mode - is this correct?

I’ve been getting an error related to the pipeline:

extraneous argument label 'pipeline:'

My call to set up the aggregation is:

let result = collection.aggregate(
  pipeline: [aggregationPipeline]

aggregationPipeline is a BSONDocument.

I’ve got loads of systems that have aggregations running with Mongoid, or Elixir, but I’m hoping to move these to Swift once I get the configuration correct.


1 Like

Hi @Mark_Windrim!

Both the sync and async APIs support aggregation via MongoCollection.aggregate.

I believe the problem with your code above is that you do not need to specify the argument label for the pipeline. It should be sufficient to just do

let result = collection.aggregate([aggregationPipeline])

I think we should add an aggregation example to our docs, I’ve opened SWIFT-1311 about this. In the meantime, here’s one:

import MongoSwiftSync

let client = try MongoClient()
let db = client.db("home")
let collection = db.collection("kittens")

try collection.insertMany([
    ["name": "Roscoe", "color": "orange"],
    ["name": "Chester", "color": "tan"],
    ["name": "Petey", "color": "black"],
    ["name": "Ginger", "color": "orange"]

let results = try collection.aggregate([
    ["$match": ["color": "orange"]],
    ["$project": ["name": 1, "color": 1, "_id": 0]]

// prints:
// {"name":"Roscoe","color":"orange"}
// {"name":"Ginger","color":"orange"}
for result in results {
    print(try result.get())

I will also note, in case it’s helpful, you can optionally specify a custom Codable type that the resulting documents from the aggregation should be decoded to, by passing it into aggregate like:

let result = collection.aggregate([aggregationPipeline], withOutputType: MyType.self)

I hope that helps! Let me know if you have any more questions.


Thanks for this. I was aware of the “withOutputType” feature - I 've been using Codable entirely through our development. Your suggestion worked like a charm - dropping the “pipeline:” was the issue.


1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.