MongoDB - Запрос документов

Здравствуйте, будущие маги баз данных! Сегодня мы погружаемся в захватывающий мир MongoDB и учимся как запрашивать документы. Как ваш доброжелательный соседский учитель компьютера, я здесь, чтобы провести вас через это путешествие, шаг за шагом. Так что натяните ваши виртуальные каски, и давайте начнем исследовать!

MongoDB - Query Document

Метод find()

Метод find() resembles a treasure hunt in MongoDB. It helps us search for documents in a collection. Imagine you have a collection called "students" in your school database. Let's see how we can use find() to retrieve information.

db.students.find()

This simple line of code will return all documents in the "students" collection. It's like asking, "Show me all the students!"

But what if we want to be more specific? Let's say we want to find all students named "John":

db.students.find({name: "John"})

This query will return all documents where the name field is "John". It's as if we're asking, "Can you show me all the Johns in the class?"

Метод pretty()

Now, let's make our results look nice and tidy with the pretty() method. It's like giving our data a fancy makeover!

db.students.find().pretty()

This will display the results in a formatted way, making it easier for us to read. It's like organizing your messy room – suddenly everything looks much better!

Метод findOne()

Sometimes, we just want to find one document. That's where findOne() comes in handy. It's like picking the first apple from the tree.

db.students.findOne({name: "Sarah"})

This will return the first document it finds where the name is "Sarah". If there are multiple Sarahs, it will only show the first one it encounters.

Эквиваленты операторов WHERE из RDBMS в MongoDB

Now, let's compare MongoDB queries to SQL WHERE clauses. It's like translating between two languages!

SQL WHERE Clause MongoDB Equivalent
WHERE name = "John" {name: "John"}
WHERE age > 25 {age: {$gt: 25}}
WHERE age >= 25 {age: {$gte: 25}}
WHERE age < 25 {age: {$lt: 25}}
WHERE age <= 25 {age: {$lte: 25}}
WHERE age != 25 {age: {$ne: 25}}

AND в MongoDB

In MongoDB, we can combine conditions using AND logic. It's like saying, "I want this AND that."

db.students.find({name: "John", age: 20})

This query will find all documents where the name is "John" AND the age is 20.

OR в MongoDB

Sometimes we want to find documents that match either one condition OR another. MongoDB has us covered!

db.students.find({$or: [{name: "John"}, {age: 20}]})

This query will find all documents where the name is "John" OR the age is 20.

Использование AND и OR вместе

We can even combine AND and OR conditions. It's like creating a complex treasure map!

db.students.find({
grade: "A",
$or: [{name: "John"}, {age: 20}]
})

This query will find all documents where the grade is "A" AND (the name is "John" OR the age is 20).

NOR в MongoDB

NOR is like saying "not this and not that". It's the opposite of OR.

db.students.find({
$nor: [{name: "John"}, {age: 20}]
})

This query will find all documents where the name is NOT "John" AND the age is NOT 20.

NOT в MongoDB

Finally, we have the NOT operator, which is like saying "anything but this".

db.students.find({
name: {$not: {$eq: "John"}}
})

This query will find all documents where the name is NOT "John".

And there you have it, my dear students! We've journeyed through the land of MongoDB queries, from simple finds to complex logical operations. Remember, practice makes perfect, so don't be afraid to experiment with these queries. Who knows? You might uncover some hidden treasures in your data!

Before we wrap up, let's have a quick pop quiz. Can you write a query to find all students who are either 18 years old OR named "Emma" AND have a grade of "B"? Give it a try, and don't forget to use the pretty() method to make your results look spiffy!

Happy querying, future database masters!

Credits: Image by storyset