A
A
Astral1004982020-01-01 22:09:32
Node.js
Astral100498, 2020-01-01 22:09:32

How to remake a database query (mongodb)?

Hello. I have a collection which contains the following records.

{
    "_id": {
        "$oid": "12d61624226cf313381508a1"
    },
    "size": 222,
    "ipTo": "772.22.122.0",
    "ipFrom": "372.22.122.0",
    "protocol": "UDP",
    "__v": 0
}
{
    "_id": {
        "$oid": "12d61624226cf313381508a1"
    },
    "size": 111,
    "ipTo": "772.22.122.0",
    "ipFrom": "372.22.122.0",
    "protocol": "UDP",
    "__v": 0
}
{
    "_id": {
        "$oid": "12d61624226cf313381508a1"
    },
    "size":42,
    "ipTo": "112.42.142.0",
    "ipFrom": "372.22.122.0",
    "protocol": "tcp",
    "__v": 0
}


I made a query that counts the number of duplicates, as well as the sum of the packet sizes, and writes this to a new collection
mongoNetworkCollection.aggregate([
//     {$limit:countDocuments},
//     { $group: {
//           _id: {IpTO:"$IpTo", IpFROM:"$IpFrom", protocol:"$Protocol"},
//           dups: { "$addToSet": "$_id" },
//           count: { "$sum": 1 },
//           total:{"$sum":"$Size"}
//     }},
//     { $project: { array: "$_id", _id: { $arrayElemAt: [ "$dups", 0 ] },count:"$count",size:"$total",date:{$substr:[(moment(new Date()).format('YYYY-MM-DD HH:mm:ss')),0,-1]}} },
//   ],(err,results) =>{})


The aggregation result is the following
{
    "_id": {
        "$oid": "12d61624226cf313381508a1"
    },
    "size": 333,
   "count": 2,
   "date": 1692142422,
"array":[{
    "ipTo": "772.22.122.0",
    "ipFrom": "372.22.122.0",
    "protocol": "UDP",
}],
    "__v": 0
}
{
    "_id": {
        "$oid": "12d61624226cf313381508a1"
    },
    "size": 42,
   "count": 1,
   "date": 1692142422,
"array":[{
    "ipTo": "112.42.142.0",
    "ipFrom": "372.22.122.0",
    "protocol": "tcp",
}],
    "__v": 0
}


Help me change the query so that the new collection is written like this
{
    "_id": {
        "$oid": "12d61624226cf313381508a1"
    },
"date": 1692142422,
"array":[{
    "ipTo": "112.42.142.0",
    "ipFrom": "372.22.122.0",
    "protocol": "tcp",
    "size": 42,
   "count": 1,
},
{
    "ipTo": "772.22.122.0",
    "ipFrom": "372.22.122.0",
    "protocol": "UDP",
   "size": 333,
   "count": 2,
}
.......... и так далее 
],
    "__v": 0
}

That is, to have one record with an array of all duplicates and their number and size

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question