Using aggregation query to get list of users with total transaction count and transaction detail as embedded document

Nagesh Jha

I am trying to get a list of users with total transaction count and each user should have latest transaction detail as embedded object using MongoDB's aggregate pipelines to fetch results in GET API.

I have the following database schema:

User: _id, name, phone, address

Product: _id, name, unit_price, description

Transaction: _id, date, product_id(ref to Product), user_id(ref to User), quantity, total_price


Expected Response JSON

[
    {
        name:"",
        phone:"",
        address:"",
        total_transaction:
        latest_transaction_detail: {
            product_id:
            quantity:
            total_price:                                                        
        }
    },
    {
        name:"",
        phone:"",
        address:"",
        total_transaction:
        latest_transaction_detail: {
            product_id:
            quantity:
            total_price:                                                        
        }
    }
]

How do I generate an aggregate query to return the above?

matthPen

You can achieve this by running an aggregation query.

  • A lookup stage will join your User collection with your Transaction collection (no need to join Product in your expected result). Its pipeline is splitted with $facet, for both get the count result and the latest transaction for that user

  • A project stage will reshape your data and extract array elements to documents.

Here's such a query :

db.User.aggregate(
[
    {
        $lookup: 
         {
            from: "Transaction",
           let: { userId: "$_id" },
            pipeline: [ 
            {$facet:
              {count:[{$match:{$expr:{$eq:["$$userId","$user_id"]}}}, {$count:"total_transaction"}],
                latest:[
                {$match:{$expr:{$eq:["$$userId","$user_id"]}}},
                {$sort:{date:-1}},
                {$limit:1}]
            } }],
            as: "transactions"
         }
    },
    {
        $project: {
          last_name:1,
          phone:1,
          address:1,
            total_transaction : {
              $let:{
                vars:{
                  count:{
                    $arrayElemAt:["$transactions.count",0]
                    }
                  },
                in:{
                  $arrayElemAt:["$$count.total_transaction",0]
                  }
                }
              },
              latest_transaction : {
              $let:{
                vars:{
                  latest:{
                    $arrayElemAt:["$transactions.latest",0]
                    }
                  },
                in:{
                  $arrayElemAt:["$$latest",0]
                  }
                }


              },    
            }
        },
    ]
);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to paginate aggregation query results in MongoDB and get a total document count (Node.js + Mongoose)?

Is it possible to get the total count of transaction and group by 15 mins interval

sql query to get the transaction for all the users having specific timestamp

Split AMEX Transaction detail strings using regex

Read an additional document in a transaction after using one transaction.get already

Get transaction details using transaction ID - Paypal

Count Total Users and Clan using MySQLI in One query

Editing a Document based on query result in Firestore Transaction

mongodb aggregation get the total number of matched document

Query Embedded Document List in MongoEngine

Get the root transaction using SQL

I am trying to find a way to get the total transaction number for a list of Ethereum addresses

get a count of users in all OUs and total the count

Get affected rows count after sqlite transaction

Get Updated Row Count in Transaction Scope

How to get transaction count with laravel eloqueent

Get Paypapl Donation Transaction Detail in Html with Donation Button Implemented

Want to delete existing document from folder and database values from table using transaction in hibernate query

SQL Query to get a count where transaction_date is in between first day of the month and last day of the month

Get the error when execute transaction query in php

How to get current query inside a transaction

count product qty in sub document mongodb transaction in one month

Get total count and total absents in one query

How get users emails in though aggregation query

How to get the list of items in a transaction in package arules

How to get Ethereum transaction list by address

Inserting a document in a transaction in MongoDB?

Get total monthly transaction from sub queries in sql

Document Count in keyword buckets from list in document as aggregation in Elasticsearch