MongoDB aggregation framework with Official Mongodb driver

Hi.. I'm just learning about the Mongodb driver for Rust. I'm used to mongodb before, and I often use aggregation framework from mongodb to execute complex queries.

Unfortunately, I can't find any example for its implementation from web nor the driver's documentation. this is the best explanation that the driver give :

    /// Runs an aggregation operation.
    /// See the documentation [here]( for more
    /// information on aggregations.
    pub async fn aggregate(
        pipeline: impl IntoIterator<Item = Document>,
        options: impl Into<Option<AggregateOptions>>,
    ) -> Result<Cursor> {
        let mut options = options.into();
            [read_concern, write_concern, selection_criteria]

        let aggregate = Aggregate::new(self.namespace(), pipeline, options);
        let client = self.client();
            .map(|(spec, session)| Cursor::new(client.clone(), spec, session))

AFAIK, the impl IntoIterator<Item = Document> line in pipelines field means that it only accepts an array vec<> that implements IntoIterator. I have no idea what the rest of the codes means.

Would someone be kind enough to give us an example for pipelines and options field ?

The IntoIterator<Item = Document> trait means "any iterable type that iterates over documents". While this can be a Vec<Document>, it can also be many other types, such as:

  • VecDeque<Document>
  • iter::once(some_document)
  • std::array::IntoIter::new([a, b, c])
  • iter::repeat_with(|| make_document())
  • And so on and so on...

Into<Option<AggregateOptions>> means any type that can be converted into AggregateOptions. This includes Option<AggregateOptions> and AggregateOptions, and its main purpose is to save you having to type Some(options) - you can simply write options instead.

1 Like