A
A
Astral1004982020-12-13 13:58:50
Node.js
Astral100498, 2020-12-13 13:58:50

How to group records in MongoDB?

Good afternoon. I have many entries in my collection. Some entries are the same, only the size field is different.

Example entries

{
    "_id": {
        "$oid": "5fc3695ae110660e88c402921"
    },
    "ip": "112.0.1.1",
    "port1": "2222",
    "ip": "172.22.122.0",
    "port2": "172.22.122.0",    
    "protocol": "TCP",
    "size": "241",
    "__v": 0
}
{
    "_id": {
        "$oid": "5fc3695ae110660e88c402921"
    },
    "ip": "112.0.1.1",
    "port1": "2222",
    "ip": "172.22.122.0",
    "port2": "172.22.122.0",    
    "protocol": "TCP",
    "size": "55",
    "__v": 0
}


And there are hundreds of such records. Can I group them? I need to get for example the first 100 records. Count the number of such records that have the same IP and IP2 fields and add up all the file sizes, and then delete the same ones and leave only one record like this?

{
    "_id": {
        "$oid": "5fc3695ae110660e88c402921"
    },
    "ip": "112.0.1.1",
    "port1": "2222",
    "ip": "172.22.122.0",
    "port2": "172.22.122.0",    
    "protocol": "TCP",
    "size": "ВОТ ТУТ СУММА",
"count": "ВОТ ТУТ количество одинаковых записей",
    "__v": 0
}


I am using moongose ​​and nodejs. How to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuriy Vorobyov, 2020-12-13
@YuriyVorobyov1333

The best option would be to use aggregations .
See how the commands work: $group , $sum , $project , $lookup and $cond .
I think this gentleman's set is more than enough to solve the
Luck problem)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question