Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Nested OR/AND Where?

Tags:

mongodb

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"
   )
like image 806
Steven Avatar asked Apr 16 '14 19:04

Steven


People also ask

Where can I find nested documents in MongoDB?

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.

Can we use where clause in MongoDB?

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.

Can we create nested collection in MongoDB?

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.


1 Answers

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.

like image 180
Catalin MUNTEANU Avatar answered Oct 11 '22 03:10

Catalin MUNTEANU