Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
express mongoDB aggregation sum

I have many records in my mongodb collection and I need to recount some information.

records format:

{
    "_id" : someId,
    "targetFrom" : ObjectId("603e0355e805140334e79438"),<-- this is ID for search
    "targetTo" : null,
    "operationPaid" : true,
    "type" : "coming", <--- type
    "moneyAccount" : someId,
    "agent" : null,
    "sum" : 5000, <--- sum
}
{
    "_id" : someId,
    "targetFrom" : null,
    "targetTo" : null,
    "operationPaid" : true,
    "type" : "out", <--- type
    "moneyAccount" : someId,
    "agent" : ObjectId("603e0355e805140334e79438"),<-- this is ID for search
    "sum" : 3000, <--- sum
}

so, I need to group by records TYPE and get SUM for id ObjectId("603e0355e805140334e79438"), but id for search can be field targetFrom or targetTo or agent

for this example I need to get result 2000

sum 5000 is coming and sum 3000 is out with

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Query

  • match the Id in one of the 3 possible fields
  • group by null (all collection 1 group), if type="out" i subtract the sum field else i add to sum field

Test code here

aggregate(
[{"$match":
  {"$expr":
   {"$or":
    [{"$eq":["$targetFrom", ObjectId("603e0355e805140334e79438")]},
     {"$eq":["$targetTo", ObjectId("603e0355e805140334e79438")]},
     {"$eq":["$agent", ObjectId("603e0355e805140334e79438")]}]}}},
 {"$group":
  {"_id":null,
   "sum":
   {"$sum":
    {"$cond":
     [{"$eq":["$type", "out"]}, {"$subtract":[0, "$sum"]}, "$sum"]}}}}])
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda