1

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.

3

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.