Database

db={"orders":[{"_id":1,"item":"almonds","price":12,"quantity":2,"customer_id":1,"created_at":ISODate("2024-06-01T00:00:00Z")},{"_id":2,"item":"pecans","price":20,"quantity":1,"customer_id":1,"created_at":ISODate("2024-06-02T00:00:00Z")},{"_id":3,"item":"pecans","price":20,"quantity":1,"customer_id":3,"created_at":ISODate("2024-06-03T00:00:00Z")}],"customers":[{"_id":1,"name":"alice"},{"_id":2,"name":"bob"},{"_id":3,"name":"charlie"}]}

Query

db.customers.aggregate([{"$lookup":{"from":"orders","localField":"_id","foreignField":"customer_id","as":"orders"}},{"$addFields":{"total_orders":{$size:"$orders"}}},{$unwind:{path:"$orders",preserveNullAndEmptyArrays:true}},{$group:{_id:"$_id",name:{$first:"$name"},first_order:{$min:"$orders.created_at"},last_order:{$max:"$orders.created_at"},total_orders:{$first:"$total_orders"}}}])

Result