MongoDB Query and Filtering Techniques
MongoDB Query and Filtering Techniques
What is MongoDB Query?
MongoDB is a NoSQL-based database that allows you to query data quickly and flexibly. With MongoDB queries, you can select, filter, and rapidly retrieve documents in your collection based on various criteria. MongoDB query and filtering operations help you access the data exactly when you need it and bring only what you want.
Basic Query and Filtering Usage
To create a MongoDB query, the find() method is actively used. Within this method, you can work with various filter queries. In basic filtering, equality, greater/less than comparisons and logical operators are used.
Simple Filtering
// List users whose 'yas' field is 18
const results = await db.kullanicilar.find({ yas: 18 }).toArray();
console.log(results);
Filtering with Comparison Operators
// Get users whose 'yas' is greater than 18
const adults = await db.kullanicilar.find({ yas: { $gt: 18 } }).toArray();
Composite and Logical Filters
// List users with 'yas' greater than 25 and 'sehir' is Istanbul
const filtered = await db.kullanicilar.find({
yas: { $gt: 25 },
sehir: "Istanbul"
}).toArray();
// Get users with 'yas' less than 30 or 'aktif' is false
const result = await db.kullanicilar.find({
$or: [
{ yas: { $lt: 30 } },
{ aktif: false }
]
}).toArray();
Advanced MongoDB Query Techniques
In MongoDB query and filtering applications, it is also possible to do string matching, search in arrays, and access subdocuments. Especially operators like $in, $regex, and $elemMatch provide advanced filtering capabilities.
Array Filtering Example
// Get users who have 'yazılım' among their interests
const softwareDevs = await db.kullanicilar.find({ ilgiAlanlari: "yazilim" }).toArray();
Text Search with Regex
// Get users whose name starts with 'Ahm'
const names = await db.kullanicilar.find({ isim: { $regex: "^Ahm" } }).toArray();
Conclusion and Tips
MongoDB query and filtering techniques help you perform efficient and fast searches within your dataset. As shown in the code, they can be customized with different operators and combinations can be created as needed. Creating the right query is critical for performance and scalability. Using the official MongoDB documentation is a good guide for more complex queries.

Yorum Gönder