Clutch
Clutch

Reputation: 7600

Need to add a "generated value" to the results in MongoDB

I have a query

[ { "$match" : { "vm_id" : "218276"}},{ "$group" : { "_id" : { "$dayOfMonth" : "$ts"} , "public_tx_total" : { "$sum" : "$interface_public_tx_bytes"} , "public_rx_total" : { "$sum" : "$interface_public_rx_bytes"} , "private_tx_total" : { "$sum" : "$interface_private_tx_bytes"} , "private_rx_total" : { "$sum" : "$interface_private_rx_bytes"} , "count" : { "$sum" : 1}}},{ "$sort" : { "_id" : 1}} ]

where I want to add a key that takes $ts and pulls the year out of and add it to the results

year: {$year: "$ts"}

I 'm not sure where to place the snippet without causing an error.

Upvotes: 0

Views: 48

Answers (1)

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

You can do it by adding the following command into the group query.

"year" : {$first : { $year:"$ts"}}

Your query will look like :

[
  {"$match":{"vm_id":"218276"}},
  {"$group":{"_id":{"$dayOfMonth":"$ts"}, 
    "year":{$first:{$year:"$ts"}}, 
    "public_tx_total":{"$sum":"$interface_public_tx_bytes"}, 
    "public_rx_total":{"$sum":"$interface_public_rx_bytes"}, 
    "private_tx_total":{"$sum":"$interface_private_tx_bytes"}, 
    "private_rx_total":{"$sum":"$interface_private_rx_bytes"}, 
    "count":{"$sum":1}}},
  {"$sort":{"_id":1}}
]

Upvotes: 1

Related Questions