Database

Overview of the routing configuration

Database

Home documentation

1. What is a Collection in MongoDB?

In MongoDB, a collection is a grouping of MongoDB documents. It is roughly analogous to a table in relational databases. Each document in a collection is a set of key-value pairs, and each collection can contain documents of varying structures.

How Does DBCollection Fit In?

The DBCollection class abstracts the basic operations you can perform on a MongoDB collection. It provides methods for:

  • Checking if a document exists by ID or other fields
  • Counting documents
  • Deleting documents
  • Updating documents

Example: Using DBCollection

Here's a practical example showing how to use DBCollection:

import 'package:mongo_dart/mongo_dart.dart';

class PostCollection extends DBCollection {
  PostCollection(Db db) : super(name: 'post', db: db);

  // Add a new post
  Future<void> addPost(Map<String, dynamic> postData) async {
    await collection.insertOne(postData);
  }

  // Check if a post exists by slug
  Future<bool> existSlug(String slug) async {
    return await exist('slug', slug);
  }

  // Get all posts with optional filtering
  Future<List<Map<String, dynamic>>> getAllPosts({Map<String, Object?>? filter}) async {
    return await collection.find(filter ?? {}).toList();
  }
}

// Usage
var db = Db('mongodb://localhost:27017/your_database');
await db.open();
var posts = PostCollection(db);

// Add a post
await posts.addPost({
  'title': 'New Post',
  'slug': 'new-post',
  'content': 'This is a new post.',
});

// Check if a slug exists
bool exists = await posts.existSlug('new-post');
print(exists); // true or false

// Get all posts
List<Map<String, dynamic>> allPosts = await posts.getAllPosts();
print(allPosts);

2. What is a Model in MongoDB?

A model represents a structure of documents in a MongoDB collection. It defines the schema or shape of documents within a collection. In the context of your application, DBModel is an abstract class that defines how a model can be converted to a format suitable for MongoDB operations.

How Does DBModel Fit In?

The DBModel class provides methods for:

  • Converting the model to a Map: toParams method allows converting an instance of the model to a Map that can be stored in MongoDB.
  • Batch Conversion: toListParams method allows converting a list of models to a list of Maps.

Example: Using PostModel

Here's how you can use PostModel to interact with MongoDB:

import 'package:json_annotation/json_annotation.dart';
import 'package:mongo_dart/mongo_dart.dart';

part 'post_model.g.dart';

@JsonSerializable()
class PostModel implements DBModel {
  @JsonKey(name: '_id')
  final String id;
  final String title;
  final String slug;
  final String content;
  final String type;
  DateTime? createTime;
  final String thumbnailId;
  final String thumbnailUrl;
  final List<String> categories;

  PostModel({
    this.id = "",
    this.title = "",
    this.slug = "",
    this.content = "",
    this.type = "post",
    this.createTime,
    this.thumbnailUrl = '',
    this.thumbnailId = '',
    this.categories = const [],
  }) {
    createTime = createTime ?? DateTime.now();
  }

  factory PostModel.fromJson(Map<String, dynamic> json) =>
      _$PostModelFromJson(json);

  @override
  Future<Map<String, Object?>> toParams({Db? db}) async {
    // Implement conversion logic
    return {
      'id': id,
      'title': title,
      'slug': slug,
      'content': content,
      'type': type,
      'createTime': createTime?.toIso8601String(),
      'thumbnailId': thumbnailId,
      'thumbnailUrl': thumbnailUrl,
      'categories': categories,
    };
  }
}

// Usage
var post = PostModel(
  id: ObjectId().toHexString(),
  title: 'My Post',
  slug: 'my-post',
  content: 'Content of my post',
);

Map<String, Object?> postParams = await post.toParams();
print(postParams);

3. What is DQ (Query Builder)?

The DQ class is a utility for constructing MongoDB queries in a more readable and structured way. It helps you build queries using various operations like equality checks, logical operations, and pattern matching.

How Does DQ Fit In?

The DQ class simplifies query construction by providing static methods to:

  • Create Queries: For matching specific values, logical operations, or pattern matching.
  • Aggregation: For grouping and sorting documents.

Example: Using DQ for Queries

Here's how to use DQ to build queries and interact with MongoDB:

import 'package:mongo_dart/mongo_dart.dart';
import 'package:webapp/wa_tools.dart';

// Initialize the MongoDB database connection
var collection = db.collection('post');

// Build a query to find posts with a specific slug
var query = DQ.field('slug', DQ.eq('my-post'));
var results = await collection.find(query).toList();
print(results);

// Build a query with pattern matching
var patternQuery = DQ.field('title', DQ.like('Post'));
var patternResults = await collection.find(patternQuery).toList();
print(patternResults);

Explanation:

  • Creating Queries: Use DQ.field to build queries for specific fields. DQ.eq for equality, DQ.like for pattern matching.
  • Executing Queries: Pass the query to the find method of the MongoDB collection to retrieve documents matching the criteria.

In summary, these components (DBCollection, DBModel, and DQ) work together to manage MongoDB collections, define document structures, and construct queries efficiently. By using these abstractions, you can streamline CRUD operations and queries in your application.