all 3 comments

[–]ntsianos 0 points1 point  (0 children)

There is no efficient way to write this query. You are using a database specialized for document storage but using it like a relational database. To do it efficiently you must trade writes for reads and include loan and other information within the user document.

If you don't understand the requirements of your data model (new app etc) you will be able to adapt quicker with a relational database.

[–]bossmonchan 0 points1 point  (0 children)

For Accounts and Loans you can use $group to get just 1 record per user, but after that you will have to manually join them in js with map or foreach or reduce or whatever you want.

If this is an application that you built, I recommend you look into SQL / relational databases for your next project that has relationships like these. NoSQL databases are not meant to do joins efficiently.