I am trying to figure out how to do nested OR/AND where queries like what you would do in MySQL
Take for example
SELECT
first_name,
id
FROM
table
WHERE
(
province = "nb" OR
province = "on"
) AND (
city = "toronto" AND
first_name = "steven"
)
Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.
Description. The MongoDB $where operator is used to match documents that satisfy a JavaScript expression. A string containing a JavaScript expression or a JavaScript function can be pass using the $where operator. The JavaScript expression or function may be referred as this or obj.
Or in other words, when a collection has a document, this document contains another document, another document contains another sub-document, and so on, then such types of documents are known as embedded/nested documents. In MongoDB, you can only nest document up to 100 levels.
The query in MongoDB looks like:
Database.collection_name.find(
// This is the condition
{
$and: [
{
$or: [
{province: 'nb'},
{province: 'on'}
]
},
{
city: "toronto"
},
{
first_name: "steven"
}
]
},
// Specify the fields that you need
{
first_name: 1,
_id: 1
}
)
Documentation for $and $or
Some examples and the official documentation for MongoDB find here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With