MongoDB Nested OR/AND Where?

2019-01-19 12:10发布

问题:

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"
   )

回答1:

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.



标签: mongodb