Created
December 27, 2016 18:26
-
-
Save slash3b/606e0e8bf564278e9aae1ed3e266a90c to your computer and use it in GitHub Desktop.
mongo double grouping example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| db.getCollection("Transaction").aggregate([ | |
| {$match: {paymentId: {$exists: true}}}, | |
| {$group: {_id: "$paymentId", id: {$addToSet: "$_id"}, amount: {$addToSet: "$amount"}, user: {$addToSet: "$user"}, count: {$sum: 1}}}, | |
| {$match: {count: {$gt: 1}}}, | |
| {$group: {_id: "$user", compound: { | |
| $addToSet: { | |
| "transactionIds":"$id", | |
| "amount": "$amount" | |
| } | |
| }}} | |
| ]).forEach(function (data) { | |
| // grab user | |
| var userId = data._id[0].getId(); | |
| var user = db.getCollection("User").find({ "_id":userId }).toArray(); | |
| user = user[0]; | |
| // grab product | |
| var productId = user.products[0].getId(); | |
| var product = db.getCollection("Product").find({ "_id":productId }).toArray(); | |
| product = product[0]; | |
| // dance! | |
| var withdraw = 0; | |
| for (var i = 0; i < data.compound.length; i++) { | |
| var set = data.compound[i]; | |
| var amount = set.amount[0]; | |
| var count = set.transactionIds.length - 1; | |
| withdraw += count * amount; | |
| } | |
| var total = user.balance - withdraw; | |
| var type = product.creditType + 0; | |
| var creditType = type == 1 ? "money based": "time based"; | |
| print("user email: " + user.username + ", product:" + product.name + ", " + creditType + ", remaining balance: " + total.toFixed(2)); | |
| }); | |
| mongo p1 --quiet --eval 'db.getCollection("Transaction").aggregate([ {$match: {paymentId: {$exists: true}}}, {$group: {_id: "$paymentId", id: {$addToSet: "$_id"}, amount: {$addToSet: "$amount"}, user: {$addToSet: "$user"}, count: {$sum: 1}}}, {$match: {count: {$gt: 1}}}, {$group: {_id: "$user", compound: { $addToSet: { "transactionIds":"$id", "amount": "$amount" } }}} ]).forEach(function (data) { var userId = data._id[0].getId(); var user = db.getCollection("User").find({ "_id":userId }).toArray(); user = user[0]; var productId = user.products[0].getId(); var product = db.getCollection("Product").find({ "_id":productId }).toArray(); product = product[0];var withdraw = 0; for (var i = 0; i < data.compound.length; i++) { var set = data.compound[i]; var amount = set.amount[0]; var count = set.transactionIds.length - 1; withdraw += count * amount; } var total = user.balance - withdraw; var type = product.creditType + 0; var creditType = type == 1 ? "money based": "time based"; print("user email: " + user.username + ", product:" + product.name + ", " + creditType + ", remaining balance: " + total.toFixed(2)); });' > affected_users |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment