Home > Software design >  How to find data based on sub-field name in MongoDB using Mongoose?
How to find data based on sub-field name in MongoDB using Mongoose?

Time:12-16

There is a sub-field called 'name' in MongoDB Collection (User):

[
{
    "teacher": {
        "name": "Alex",
        "email": "[email protected]"
    },
    "waiter": {
        "name": "Feliks",
        "email": "[email protected]"
    },
    "pilot": [
    {
        "name": "Sam",
        "email": "[email protected]"
    },
    {
        "name": "alice",
        "email": "[email protected]"
    }
    ],
},
{
    "teacher": {
        "name": "max",
        "email": "[email protected]"
    },
    "waiter": {
        "name": "Sam",
        "email": "[email protected]"
    },
    "pilot": [
    {
        "name": "richard",
        "email": "[email protected]"
    },
    {
        "name": "alice",
        "email": "[email protected]"
    }
    ],
}
]

How can I find data based on the field 'name'. For example, when I'm looking for 'Sam', it should return me the all documents since 'Sam' is in "waiter" and "pilot" in first and second documents respectively.

I cannot do something like:

User.find({"teacher.name": "Sam", "waiter.name": "Sam", "pilot.name": "Sam" })

This will return me nothing as it is an AND logic. What I need is an OR logic.

CodePudding user response:

You can use the $or operator. So the query should look like this:

User.find({ $or: [
                  { "teacher.name": "Sam" }, 
                  { "waiter.name": "Sam" }, 
                  { "pilot.name": "Sam" }
                 ] 
          });

Read here for me details.

  • Related