Expand description

MongoDB Cursor Pagination

Crate Docs Build Status MIT licensed

Documentation
Examples

This package provides a cursor based pagination using the mongodb driver. Essentially instead of page based pagination you receive cursors to both the start and end of the result set so that you can ensure you get the next item, even if the data changes in between requests. That said, it also provides regular ole’ page based pagination as well. If your options include skip and limit parameters then you’ll do the page based. If you leave skip off or send a cursor, then it will use that instead (and ignore the skip parameter.)

It’s based on the node.js module but written in Rust. You can read more about the concept on their blog post.

So far it only supports find. Search and aggregation will come when needed.

Usage:

The usage is a bit different than the node version. See the examples for more details and a working example.

use mongodb::{options::FindOptions, Client};
use mongodb_cursor_pagination::{FindResult, Pagination};
use bson::doc;
use serde::Deserialize;

// Note that your data structure must derive Deserialize
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct MyFruit {
    name: String,
    how_many: i32,
}

#[tokio::main]
async fn main() {
    let client = Client::with_uri_str("mongodb://localhost:27017/")
        .await
        .expect("Failed to initialize client.");
    let db = client.database("mongodb_cursor_pagination");
    let fruits = db.collection::<MyFruit>("myfruits");

    let docs = vec![
        doc! { "name": "Apple", "how_many": 5 },
        doc! { "name": "Orange", "how_many": 3 },
        doc! { "name": "Blueberry", "how_many": 25 },
        doc! { "name": "Bananas", "how_many": 8 },
        doc! { "name": "Grapes", "how_many": 12 },
    ];

    db.collection("myfruits")
        .insert_many(docs, None)
        .await
        .expect("Unable to insert data");

    // query page 1, 2 at a time
    let options = FindOptions::builder()
            .limit(2)
            .sort(doc! { "name": 1 })
            .build();

    let mut find_results: FindResult<MyFruit> = fruits
        .find_paginated(None, Some(options.clone()), None)
        .await
        .expect("Unable to find data");
    println!("First page: {:?}", find_results);

    // get the second page
    let mut cursor = find_results.page_info.end_cursor;
    find_results = fruits
        .find_paginated(None, Some(options), cursor)
        .await
        .expect("Unable to find data");
    println!("Second page: {:?}", find_results);
}

Response

The response FindResult<T> contains page info, cursors and edges (cursors for all of the items in the response).

pub struct PageInfo {
    pub has_next_page: bool,
    pub has_previous_page: bool,
    pub start_cursor: Option<String>,
    pub next_cursor: Option<String>,
}

pub struct Edge {
    pub cursor: String,
}

pub struct FindResult<T> {
    pub page_info: PageInfo,
    pub edges: Vec<Edge>,
    pub total_count: i64,
    pub items: Vec<T>,
}

Features

It has support for graphql (using juniper) if you enable the graphql flag. You can use it by just including the PageInfo into your code.

use mongodb_cursor_pagination::{PageInfo, Edge};

#[derive(Serialize, Deserialize)]
struct MyDataConnection {
    page_info: PageInfo,
    edges: Vec<Edge>,
    data: Vec<MyData>,
    total_count: i64,
}

[juniper::object]
impl MyDataConnection {
    fn page_info(&self) -> &PageInfo {
        self.page_info
    }

    fn edges(&self) -> &Vec<Edge> {
        &self.edges
    }
}

Structs

  • Represents a Cursor to an Item with no special direction. To Debug the contents, use Debug When serializing or converting to String, the Edge gets encoded as url-safe Base64 String.
  • The result of a find method with the items, edges, pagination info, and total count of objects
  • Contains information about the current Page The cursor have the respecting direction to be used as is in an subsequent find: start_cursor: Backwards end_cursor: Forward

Enums

  • Cursor to an item with direction information. Serializing pretains the direction Information. To send only the Cursor use to_string which drops the direction information

Traits