use mongodb::bson::oid::ObjectId;
use mongodb::bson::{Bson, DateTime, Document, doc};
use mongodb::error::Result;
pub struct FilterBuilder {
conditions: Vec<Document>,
}
impl FilterBuilder {
pub fn new() -> Self {
Self {
conditions: Vec::new(),
}
}
pub fn with_regex(mut self, field: &str, value: Option<&str>) -> Self {
if let Some(v) = value {
if !v.is_empty() {
self.conditions.push(doc! {
field: { "$regex": v, "$options": "i" }
});
}
}
self
}
pub fn with_date_range(mut self, field: &str, start: Option<&str>, end: Option<&str>) -> Self {
let mut date_filter = doc! {};
if let Some(start_str) = start {
if let Ok(start_date) = DateTime::parse_rfc3339_str(start_str) {
date_filter.insert("$gte", start_date);
}
}
if let Some(end_str) = end {
if let Ok(end_date) = DateTime::parse_rfc3339_str(end_str) {
date_filter.insert("$lte", end_date);
}
}
if !date_filter.is_empty() {
self.conditions.push(doc! { field: date_filter });
}
self
}
pub fn try_with_date_range(
mut self,
field: &str,
start: Option<&str>,
end: Option<&str>,
) -> Result<Self> {
let mut date_filter = doc! {};
if let Some(start_str) = start {
let start_date = DateTime::parse_rfc3339_str(start_str)?;
date_filter.insert("$gte", start_date);
}
if let Some(end_str) = end {
let end_date = DateTime::parse_rfc3339_str(end_str)?;
date_filter.insert("$lte", end_date);
}
if !date_filter.is_empty() {
self.conditions.push(doc! { field: date_filter });
}
Ok(self)
}
pub fn with_field(mut self, field: &str, value: Option<impl Into<Bson>>) -> Self {
if let Some(v) = value {
self.conditions.push(doc! { field: v.into() });
}
self
}
pub fn with_id_field(mut self, field: &str, id: Option<&str>) -> Self {
if let Some(id_str) = id {
if let Ok(oid) = ObjectId::parse_str(id_str) {
self.conditions.push(doc! { field: oid });
}
}
self
}
pub fn try_with_id_field(mut self, field: &str, id: Option<&str>) -> Result<Self> {
if let Some(id_str) = id {
let oid = ObjectId::parse_str(id_str).map_err(|e| mongodb::error::Error::custom(e))?;
self.conditions.push(doc! { field: oid });
}
Ok(self)
}
pub fn with_gt(mut self, field: &str, value: impl Into<Bson>) -> Self {
self.conditions
.push(doc! { field: { "$gt": value.into() } });
self
}
pub fn with_gte(mut self, field: &str, value: impl Into<Bson>) -> Self {
self.conditions
.push(doc! { field: { "$gte": value.into() } });
self
}
pub fn with_lt(mut self, field: &str, value: impl Into<Bson>) -> Self {
self.conditions
.push(doc! { field: { "$lt": value.into() } });
self
}
pub fn with_lte(mut self, field: &str, value: impl Into<Bson>) -> Self {
self.conditions
.push(doc! { field: { "$lte": value.into() } });
self
}
pub fn with_ne(mut self, field: &str, value: impl Into<Bson>) -> Self {
self.conditions
.push(doc! { field: { "$ne": value.into() } });
self
}
pub fn with_range(mut self, field: &str, min: impl Into<Bson>, max: impl Into<Bson>) -> Self {
self.conditions.push(doc! {
field: {
"$gte": min.into(),
"$lte": max.into()
}
});
self
}
pub fn with_in<T: Into<Bson>>(mut self, field: &str, values: Vec<T>) -> Self {
let bson_values: Vec<Bson> = values.into_iter().map(|v| v.into()).collect();
self.conditions.push(doc! { field: { "$in": bson_values } });
self
}
pub fn with_nin<T: Into<Bson>>(mut self, field: &str, values: Vec<T>) -> Self {
let bson_values: Vec<Bson> = values.into_iter().map(|v| v.into()).collect();
self.conditions
.push(doc! { field: { "$nin": bson_values } });
self
}
pub fn with_id_in(mut self, field: &str, ids: Vec<&str>) -> Self {
let oids: Vec<Bson> = ids
.into_iter()
.filter_map(|id| ObjectId::parse_str(id).ok())
.map(|oid| oid.into())
.collect();
if !oids.is_empty() {
self.conditions.push(doc! { field: { "$in": oids } });
}
self
}
pub fn try_with_id_in(mut self, field: &str, ids: Vec<&str>) -> Result<Self> {
let oids: Vec<Bson> = ids
.into_iter()
.map(|id| ObjectId::parse_str(id).map(|oid| oid.into()))
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(|e| mongodb::error::Error::custom(e))?;
if !oids.is_empty() {
self.conditions.push(doc! { field: { "$in": oids } });
}
Ok(self)
}
pub fn or(conditions: Vec<Document>) -> Self {
let mut builder = Self::new();
if !conditions.is_empty() {
builder.conditions.push(doc! { "$or": conditions });
}
builder
}
pub fn or_builders(builders: Vec<FilterBuilder>) -> Self {
let conditions: Vec<Document> = builders
.into_iter()
.map(|b| b.build())
.filter(|d| !d.is_empty())
.collect();
Self::or(conditions)
}
pub fn with_or(mut self, conditions: Vec<Document>) -> Self {
if !conditions.is_empty() {
self.conditions.push(doc! { "$or": conditions });
}
self
}
pub fn nor(conditions: Vec<Document>) -> Self {
let mut builder = Self::new();
if !conditions.is_empty() {
builder.conditions.push(doc! { "$nor": conditions });
}
builder
}
pub fn with_not(mut self, field: &str, condition: Document) -> Self {
self.conditions.push(doc! { field: { "$not": condition } });
self
}
pub fn with_exists(mut self, field: &str, exists: bool) -> Self {
self.conditions.push(doc! { field: { "$exists": exists } });
self
}
pub fn with_type(mut self, field: &str, bson_type: &str) -> Self {
self.conditions.push(doc! { field: { "$type": bson_type } });
self
}
pub fn with_all<T: Into<Bson>>(mut self, field: &str, values: Vec<T>) -> Self {
let bson_values: Vec<Bson> = values.into_iter().map(|v| v.into()).collect();
self.conditions
.push(doc! { field: { "$all": bson_values } });
self
}
pub fn with_elem_match(mut self, field: &str, condition: Document) -> Self {
self.conditions
.push(doc! { field: { "$elemMatch": condition } });
self
}
pub fn with_size(mut self, field: &str, size: i32) -> Self {
self.conditions.push(doc! { field: { "$size": size } });
self
}
pub fn with_text_search(mut self, search: &str) -> Self {
self.conditions.push(doc! {
"$text": {
"$search": search
}
});
self
}
pub fn with_text_search_lang(mut self, search: &str, language: &str) -> Self {
self.conditions.push(doc! {
"$text": {
"$search": search,
"$language": language
}
});
self
}
pub fn build(self) -> Document {
match self.conditions.len() {
0 => doc! {},
1 => self.conditions.into_iter().next().unwrap(),
_ => doc! { "$and": self.conditions },
}
}
}
impl Default for FilterBuilder {
fn default() -> Self {
Self::new()
}
}