Skip to content

Instantly share code, notes, and snippets.

@njb-said
Last active August 30, 2017 21:54
Show Gist options
  • Save njb-said/ddd0c1de9a95e634cf0d4f1b48429b9c to your computer and use it in GitHub Desktop.
Save njb-said/ddd0c1de9a95e634cf0d4f1b48429b9c to your computer and use it in GitHub Desktop.
test for aggregating outstanding orders from mongo shell
db.getCollection('Orders').aggregate([
{
'$match' : { 'products.outstanding' : { $gt: 0 }, 'status' : {$nin:['cancelled', 'dispatched']} }
},
{
'$unwind' : '$products'
},
{
'$group' : {
'_id': '$products._id',
outstanding: {
'$sum' : '$products.outstanding'
},
totalOrders: {
'$sum' : NumberInt(1)
},
ids: {
'$addToSet' : '$_id'
}
}
}
])
// Several fields omitted
// This is a mongo document
// In reality comments aren't allowed
{
"_id" : ObjectId("id-here"),
"id" : 1,// used for display to users only
"products" : [
{
"_id" : "product-mongo-id",
"quantity" : 15,
"outstanding" : 10,
"allocations" : [
{
"_id" : "stock-mongo-id",
"number" : 5
}
]
}
],
"customer" : "mongo-id",
"deliveryAddress" : "address-id",
"date" : ISODate("2017-08-30T14:52:32.684Z"),
"lastUpdated" : ISODate("2017-08-30T14:52:32.684Z"),
"origin" : "origin-id",
"status" : "in-progress"
}
db.getCollection('Orders').find({'products._id':'mongo-id-of-product', 'products.outstanding' : { $gt: 0 }}, { 'products.$.outstanding' : 1})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment