R
R
Rag'n' Code Man2021-07-16 17:20:41
MongoDB
Rag'n' Code Man, 2021-07-16 17:20:41

How to create a query to MongoDB to filter by several fields at once?

I have a student object

[
  {
    "_id": "60f18b0120e927a4bf5a3654",
    "balance": 0,
    "groups": [
        "id1",
        "id2",
        "id3"
    ],
    "name": "Хабиб",
    "surname": "Нурмагомедов",
    "midname": "Абдулманапович",
    "gender": "Мужской",
    "age": "2005-05-06T00:00:00.000Z"
  }
]


And I need to do something like a filter pipeline

Which fields should be filtered by:
1) balance- Negative, positive, or both
2) gender- Male, Female, or both
3) age- There should be an array $orof conditions, let's say , we are looking for people aged 13, 15 and 19 years old. Age is stored as a date of birth in ISO format, and the algorithm for finding people of the right age works like this:
if we are looking for a person whose age is 16, then it agemust be $gte: /*какая-то дата*/and $lt: /*какая-то дата*/(Operators >, <, =, etc. are applicable to the date)
4) groups- the student in the example has only three groups - id1, id2, id3, you need to filter out students who have groups in the groups field from the id array, which we get as a filter.

Here is an example: we have three students with different list of groups
{
    groups: ["id1", "id3", "id8"]
},
{
    groups: ["id1", "id2", "id5"]
},
{
    groups: ["id6", "id7", "id8"]
}


And as input we get the following filter: And as a result we get:
["id1", "id2"]

{
    groups: ["id1", "id3", "id8"]
},
{
    groups: ["id1", "id2", "id5"]
}


In general, a student in the array of groups must have at least 1 element from the filter. I heard something about $all, but I would at least have to combine the first, second and third filters for now ...

Moreover, if there is no filter, then it just needs to not be applied (when I put an empty array without filters in $or , it gave me an error that or cannot contain an empty array)

Please help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rag'n' Code Man, 2021-07-16
@iDmitriyWinX

Ok, I found a solution - MongoDB Compass has an aggregate pipeline constructor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question