Skip to content

Pipeline API Reference ​

The AggregationPipeline struct provides a fluent builder for aggregation pipelines.

Installation ​

Add PocketDB to your Cargo.toml:

toml
[dependencies]
pocketdb = "0.1"

Or via the command line:

bash
cargo add pocketdb

Import ​

rust
use pocketdb::query::{AggregationPipeline, PipelineStage};

Creating a Pipeline ​

rust
let pipeline = AggregationPipeline::new();

Pipeline Methods ​

match_ ​

rust
pub fn match_(self, filter: Filter) -> Self

Adds a $match stage to filter documents.

rust
use pocketdb::filter;

let pipeline = pipeline.match_(filter! { "age" => >= 18 });

sort ​

rust
pub fn sort(self, fields: Vec<SortField>) -> Self

Adds a $sort stage to order documents.

rust
use pocketdb::query::{SortField, SortDirection};

let pipeline = pipeline.sort(vec![
    SortField::asc("name"),
    SortField::desc("age"),
]);

limit ​

rust
pub fn limit(self, n: usize) -> Self

Adds a $limit stage to limit the number of documents.


skip ​

rust
pub fn skip(self, n: usize) -> Self

Adds a $skip stage to skip the first n documents.


project ​

rust
pub fn project(self, projection: Projection) -> Self

Adds a $project stage to select fields.

rust
use pocketdb::query::Projection;

let pipeline = pipeline.project(Projection::include(&["name", "email"]));

unwind ​

rust
pub fn unwind(self, field: &str) -> Self

Adds an $unwind stage to deconstruct an array field, creating one document per element.


count ​

rust
pub fn count(self, field: &str) -> Self

Adds a $count stage to count documents.

rust
let pipeline = pipeline.count("total");
// Returns: [{ "total": 42 }]

lookup ​

rust
pub fn lookup(self, stage: LookupStage) -> Self

Adds a $lookup stage to join with another collection.

rust
use pocketdb::query::relationship_lookup::{LookupStage, JoinType};

let pipeline = pipeline.lookup(
    LookupStage::new("orders", "user_id", "customer_id", "purchases")
        .with_join_type(JoinType::LeftOuter)
);

add_stage ​

rust
pub fn add_stage(mut self, stage: PipelineStage) -> Self

Adds an arbitrary pipeline stage. Used for $group and other advanced stages.

rust
use pocketdb::query::{Accumulator, AccumulatorOp, PipelineStage};

let pipeline = pipeline.add_stage(PipelineStage::Group {
    id: Some("department".to_string()),
    accumulators: vec![
        Accumulator {
            field: "avg_age".to_string(),
            op: AccumulatorOp::Avg,
            input_field: "age".to_string(),
        },
    ],
});

stages ​

rust
pub fn stages(&self) -> &[PipelineStage]

Returns the list of pipeline stages.


execute ​

rust
pub fn execute(&self, docs: &[Document]) -> Vec<Document>

Executes the aggregation pipeline against the given documents and returns the results.

Parameters:

  • docs — The input documents

Returns: Vec<Document> — The aggregated results

Example:

rust
let results = pipeline.execute(&collection.all_documents());

PipelineStage Variants ​

rust
pub enum PipelineStage {
    Match(Filter),
    Group {
        id: Option<String>,
        accumulators: Vec<Accumulator>,
    },
    Sort(Vec<SortField>),
    Limit(usize),
    Skip(usize),
    Project(Projection),
    Unwind(String),
    Count(String),
    Lookup(LookupStage),
    AddFields(Vec<(String, PocketValue)>),
}

Accumulator Operations ​

rust
pub enum AccumulatorOp {
    Sum,     // Sum of numeric values
    Avg,     // Average of numeric values
    Min,     // Minimum value
    Max,     // Maximum value
    Push,    // Collect values into an array
    First,   // First value in the group
    Last,    // Last value in the group
    Count,   // Count of documents
}

SortField ​

rust
pub struct SortField {
    pub field: String,
    pub direction: SortDirection,
}

impl SortField {
    pub fn new(field: &str, direction: SortDirection) -> Self
    pub fn asc(field: &str) -> Self
    pub fn desc(field: &str) -> Self
}

Projection ​

rust
pub struct Projection { ... }

impl Projection {
    pub fn include(fields: &[&str]) -> Self
    pub fn exclude(fields: &[&str]) -> Self
    pub fn none() -> Self
    pub fn apply(&self, doc: &Document) -> Document
}

Complete Pipeline Example ​

rust
use pocketdb::{filter, PocketValue};
use pocketdb::query::{
    AggregationPipeline, PipelineStage, SortField,
    Accumulator, AccumulatorOp, Projection,
};
use pocketdb::query::relationship_lookup::{LookupStage, JoinType};

let results = collection.aggregate()
    // Filter active users
    .match_(filter! { "active" => == true })
    // Join with orders
    .lookup(
        LookupStage::new("orders", "user_id", "customer_id", "purchases")
            .with_join_type(JoinType::LeftOuter)
    )
    // Unwind orders
    .unwind("purchases")
    // Group by user, sum order amounts
    .add_stage(PipelineStage::Group {
        id: Some("name".to_string()),
        accumulators: vec![
            Accumulator {
                field: "total_spent".to_string(),
                op: AccumulatorOp::Sum,
                input_field: "purchases.amount".to_string(),
            },
            Accumulator {
                field: "order_count".to_string(),
                op: AccumulatorOp::Count,
                input_field: "purchases.amount".to_string(),
            },
        ],
    })
    // Sort by total spent descending
    .sort(vec![SortField::desc("total_spent")])
    // Limit to top 10
    .limit(10)
    // Execute against the collection
    .execute(&collection.all_documents());

Released under the MIT License. Built by Muhammad Fiaz.