Certainly! To enable filtering data in your custom database similar to MongoDB's find method, you'll need to implement a query system that allows you to specify search criteria and retrieve documents that match.
Below, I'll guide you through adding a find method to your Collection struct that accepts a query and returns matching documents. We'll start with a basic implementation that you can further expand based on your needs.
Step 1: Implement a find Method in Collection
First, add a find method to your Collection struct. This method will accept a serde_json::Value as the query and return a vector of references to matching documents.
Here's how you can define the method:
use serde_json::Value;
impl Collection {
pub fn find(&self, query: &Value) -> Vec<&Document> {
self.documents.values()
.filter(|doc| matches_query(&doc.content, query))
.collect()
}
}
Step 2: Implement the matches_query Function
Next, you'll need a helper function matches_query that checks if a document's content matches the query criteria. This function will perform a recursive comparison between the query and the document content.
Here's a basic implementation:
fn matches_query(doc: &Value, query: &Value) -> bool {
match (doc, query) {
(Value::Object(doc_obj), Value::Object(query_obj)) => {
for (key, query_value) in query_obj {
match doc_obj.get(key) {
Some(doc_value) => {
if !value_matches(doc_value, query_value) {
return false;
}
}
None => {
// Key doesn't exist in the document
return false;
}
}
}
true
},
_ => false,
}
}
fn value_matches(doc_value: &Value, query_value: &Value) -> bool {
match query_value {
// If the query value is an object, perform recursive matching (for nested fields)
Value::Object(_) => matches_query(doc_value, query_value),
// For other types, check for equality
_ => doc_value == query_value,
}
}
This function works as follows:
-
Objects: If both the document content and the query are JSON objects, it iterates over the query's key-value pairs and checks if each key exists in the document. If a key is missing or the value doesn't match, it returns false.
-
Other Types: For non-object types (e.g., strings, numbers), it directly compares the values for equality.
Step 3: Use the find Method
With the find method implemented, you can now query your collection like this:
let collection = database.get_collection("skibidi").unwrap();
// Suppose you have documents like:
// {"name": "Alice", "age": 29}
// {"name": "Bob", "age": 35}
let results = collection.find(&json!({"age": 29}));
for doc in results {
println!("Found document: {:?}", doc);
}
Example: Updating Your main Function
Here's how you might modify your main function to use the new find method:
fn main() {
let mut database = Database::new("new_one!");
let collection = database.add_collection("skibidi")
.expect("Could not add skibidi");
collection.add(json!({"name": "Alice", "age": 29}));
collection.add(json!({"name": "Bob", "age": 35}));
collection.add(json!({"name": "Charlie", "age": 29}));
let results = collection.find(&json!({"age": 29}));
for doc in results {
println!("Found document: {:?}", doc.content);
}
// Output:
// Found document: Object({"age": Number(29), "name": String("Alice")})
// Found document: Object({"age": Number(29), "name": String("Charlie")})
database.save_database().unwrap();
}
Advanced Querying (Optional)
The above implementation is basic and checks for exact matches. If you want to support more advanced querying capabilities similar to MongoDB (like range queries, $gt, $lt, etc.), you can extend the matches_query function.
Here's an example of how you might handle some simple operators:
fn matches_query(doc: &Value, query: &Value) -> bool {
match (doc, query) {
(Value::Object(doc_obj), Value::Object(query_obj)) => {
for (key, query_value) in query_obj {
match doc_obj.get(key) {
Some(doc_value) => {
if !value_matches(doc_value, query_value) {
return false;
}
}
None => return false,
}
}
true
},
_ => false,
}
}
fn value_matches(doc_value: &Value, query_value: &Value) -> bool {
match query_value {
Value::Object(query_obj) => {
for (op, value) in query_obj {
match op.as_str() {
"$gt" => {
if !compare_numbers(doc_value, value, std::cmp::Ordering::Greater) {
return false;
}
},
"$lt" => {
if !compare_numbers(doc_value, value, std::cmp::Ordering::Less) {
return false;
}
},
// Add more operators as needed
_ => return false,
}
}
true
},
_ => doc_value == query_value,
}
}
fn compare_numbers(doc_value: &Value, query_value: &Value, ord: std::cmp::Ordering) -> bool {
if let (Some(doc_num), Some(query_num)) = (doc_value.as_f64(), query_value.as_f64()) {
return match ord {
std::cmp::Ordering::Greater => doc_num > query_num,
std::cmp::Ordering::Less => doc_num < query_num,
std::cmp::Ordering::Equal => doc_num == query_num,
};
}
false
}
Using Advanced Queries
With this extended functionality, you can perform queries like:
let results = collection.find(&json!({"age": {"$gt": 30}}));
for doc in results {
println!("Found document: {:?}", doc.content);
}
// Output:
// Found document: Object({"age": Number(35), "name": String("Bob")})
Alternative Approach: Using Closures for Flexibility
If you prefer more flexibility and power, you can modify the find method to accept a closure (predicate function). This way, you can write any kind of logic for filtering.
Modify the find Method
impl Collection {
pub fn find<F>(&self, predicate: F) -> Vec<&Document>
where
F: Fn(&Document) -> bool,
{
self.documents.values()
.filter(|doc| predicate(doc))
.collect()
}
}
Using the find Method with a Closure
let results = collection.find(|doc| {
if let Some(age) = doc.content.get("age").and_then(|v| v.as_i64()) {
age == 29
} else {
false
}
});
for doc in results {
println!("Found document: {:?}", doc.content);
}
This approach gives you the power to define complex logic inline without modifying the Collection implementation.
Conclusion
By adding a find method to your Collection struct and implementing a matches_query function, you can filter documents based on query criteria similar to MongoDB. Start with the basic implementation and extend it as needed to support more complex queries.
Feel free to ask if you need further assistance or have questions about implementing specific features!