How to sum this this JSON data values below - mongodb

I am Imran, Please see the JSON data below and tell how to sum the result below:
{
"_id" : "59ae33130d83f7001112ea5e",
"user" : {
"passcode" : "****",
"operator" : "premiereservices",
"phone_num" : "8587366808",
"balance" : 1.99
},
"location_id" : "58ec4e82addba5001160fc07",
"customer_id" : "premiereservices",
"shopping_cart" : {
"item_count" : 2,
"items" : [
{
"customer_id" : "premiereservices",
"barcode" : "666",
"description" : "Test Item",
"price" : 1.99,
"taxable" : false,
"fixed_price_tax" : 0.05,
"__v" : 0
},
{
"customer_id" : "premiereservices",
"barcode" : "777",
"description" : "Test Item",
"price" : 1.99,
"taxable" : false,
"fixed_price_tax" : 0.05,
"__v" : 0
}
],
"total_due" : 4.08
},
"cart_total" : 4.08,
"Date" : "2017-09-04T23:16:03-06:00",
"__v" : 0
}
{
"_id" : "59ae38f186c7e70011a4e224",
"location_id" : "58ec522a99da86001123ec47",
"customer_id" : "premiereservices",
"user" : {
"phone_num" : "4129514766",
"balance" : 0.03
},
"cart_total" : 3.55,
"shopping_cart" : {
"items" : [
{
"barcode" : "028400020008",
"description" : "Smartfood White Cheddar Popcorn",
"price" : 1.25,
"taxable" : false,
"tax_collected" : 0
},
{
"barcode" : "012000286209",
"description" : "Pureleaf Unsweetened Tea",
"price" : 2.3,
"taxable" : false,
"tax_collected" : 0
}
]
},
"Date" : "2017-09-04T23:41:05-06:00",
"__v" : 0
}
{
"_id" : "59ae3c569ce8ec00112775d6",
"location_id" : "58ec522a99da86001123ec47",
"customer_id" : "premiereservices",
"user" : {
"phone_num" : "7192358363",
"balance" : 9.99
},
"cart_total" : 3.25,
"shopping_cart" : {
"items" : [
{
"barcode" : "10002",
"description" : "GnG Burrito Bacon/GChili/Potato",
"price" : 3.25,
"taxable" : true,
"tax_collected" : 0
}
]
},
"Date" : "2017-09-04T23:55:34-06:00",
"__v" : 0
}
Result Will be
cart_total: 10.88
price: 10.78
tax_collected: 0
Please anybody help me what will be the aggregate query functions

There you go:
db.collection.aggregate({
$project: { // for each document...
cart_total: 1, // ...keep the "cart_total" field
price: { $sum: "$shopping_cart.items.price" }, // ...sum up all "price" fields
tax_collected: { $sum: "$shopping_cart.items.tax_collected" } // ...sum up all "price" fields
}
}, {
$group: {
_id: null, // group all documents into the same bucket and sum up a bunch of values
cart_total: { $sum: "$cart_total" },
price: { $sum: "$price" },
tax_collected: { $sum: "$tax_collected" }
}
}, {
$project: {
_id: 0 // remove the "_id" field
}
})

Related

$map upto three nested array mongodb aggregation

I´m facing a challenge here. I have this collection here
{
"_id" : ObjectId("5e0ff6d424f9fc12bc3d9464"),
"name" : "Pizzaria Don Juan",
"active" : true,
"branches" : [
{
"location" : {
"type" : "Point",
"coordinates" : [ ]
},
"_id" : ObjectId("5e19cafc31d60216b8dbd649"),
"name" : "Parque da Mooca",
"address" : "Rua Dianópolis",
"addressNumber" : 1283,
"federalId" : "10.445.089/0001-44",
"complement" : "Ap 55",
"postalCode" : "03126-007",
"coveredArea" : 0,
"neighborhood" : "Parque da Mooca",
"deliveryTime" : 0,
"deliveryRate" : 0,
"standard" : false,
"city" : "Mococa",
"state" : "RJ",
"emails" : [ ],
"phones" : [ ],
"daysWeek" : [ ],
"socialMedias" : [ ],
"paymentTerms" : [ ],
"sections" : [ ]
},
{
"location" : {
"type" : "Point",
"coordinates" : [ ]
},
"_id" : ObjectId("5e19c9a531d60216b8dbd639"),
"name" : "Principal",
"address" : "Rua Nicolau Filizola",
"addressNumber" : null,
"federalId" : "10.445.089/0001-53",
"complement" : "",
"postalCode" : "05547-010",
"coveredArea" : 0,
"neighborhood" : "Jardim Rosa Maria",
"deliveryTime" : 0,
"deliveryRate" : 0,
"standard" : true,
"city" : "São Paulo",
"state" : "SP",
"emails" : [
{
"_id" : ObjectId("5e19ca9531d60216b8dbd643"),
"name" : "Contato",
"address" : "contato#pizzariadonjuan.com.br"
},
{
"_id" : ObjectId("5e19ca9531d60216b8dbd642"),
"name" : "Contato2",
"address" : "contato2#pizzariadonjuan.com.br"
}
],
"phones" : [
{
"_id" : ObjectId("5e19ca9531d60216b8dbd645"),
"name" : "Principal",
"number" : "(11) 99740-2216"
},
{
"_id" : ObjectId("5e19ca9531d60216b8dbd644"),
"name" : "Secundario",
"number" : "(11) 2562-2759"
}
],
"daysWeek" : [
{
"_id" : ObjectId("5e1cf99741c52d4a587a9162"),
"startsAt" : 64800000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a124a17fd054900a1afb2")
},
{
"_id" : ObjectId("5e1cf99741c52d4a587a9161"),
"startsAt" : 0,
"endsAt" : 0,
"opens" : false,
"dayWeekId" : ObjectId("5e1a126817fd054900a1afb3")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a9170"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a126e17fd054900a1afb4")
},
{
"_id" : ObjectId("5e1b8fac96516432845e364c"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a127517fd054900a1afb5")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916f"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a127a17fd054900a1afb6")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916e"),
"startsAt" : 64800000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a23f8bf353f493c74e8ae")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916d"),
"startsAt" : 61380000,
"endsAt" : 83154000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a2407bf353f493c74e8af")
}
],
"socialMedias" : [
{
"_id" : ObjectId("5e1d082641c52d4a587a9191"),
"socialMediaId" : ObjectId("5e10089a3330ad05d4e1867d"),
"url" : "rewrwerwerwerwerwerwerwer"
}
],
"paymentTerms" : [
{
"_id" : ObjectId("5e1d143041c52d4a587a91b7"),
"paymentTermId" : ObjectId("5e1a2277bf353f493c74e8a7")
},
{
"_id" : ObjectId("5e1d143041c52d4a587a91b6"),
"paymentTermId" : ObjectId("5e1a228cbf353f493c74e8a8")
},
{
"_id" : ObjectId("5e1d143041c52d4a587a91b5"),
"paymentTermId" : ObjectId("5e1a229ebf353f493c74e8a9")
}
],
"sections" : [
{
"_id" : ObjectId("5e1e535441c52d4a587a9208"),
"name" : "Camisetas",
"products" : [
{
"_id" : ObjectId("5e1e662f044582129844ffd5"),
"name" : "DonJuan M",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 0,
"validFrom" : ISODate("2020-01-15T01:08:49.552Z"),
"validTo" : ISODate("2020-01-15T01:08:49.552Z"),
"enabled" : true
}
]
},
{
"_id" : ObjectId("5e20ec889c05f229a484ea3d"),
"name" : "Imãs",
"products" : [
{
"_id" : ObjectId("5e20ec889c05f229a484ea3e"),
"name" : "Imã",
"description" : "Imã",
"quantityAvailable" : 0,
"image" : "",
"price" : 0,
"validFrom" : ISODate("0001-01-01T00:00:00Z"),
"validTo" : ISODate("9999-12-31T00:00:00Z"),
"enabled" : true
}
]
}
]
}
],
"users" : [
{
"_id" : ObjectId("5e10fc2adc147a373c312144")
},
{
"_id" : ObjectId("5e11ff8003eb832ef84342a6")
}
],
"socialMedias" : [
{
"_id" : ObjectId("5e165672a2204b49c892db74"),
"socialMediaId" : ObjectId("5e10089a3330ad05d4e1867d"),
"url" : "uuuutt"
},
{
"_id" : ObjectId("5e15385fb3a0aa1004ac3598"),
"socialMediaId" : ObjectId("5e1009043330ad05d4e1867f"),
"url" : "jkkjkjkjkjk"
}
],
"sections" : [
{
"_id" : ObjectId("5e15313b2e985e16ec4e7413"),
"name" : "Bebidas",
"products" : [
{
"_id" : ObjectId("5e1e6381044582129844ffc2"),
"name" : "Coca Cola Zero 2 Litros",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 18.39,
"validFrom" : ISODate("1970-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
},
{
"_id" : ObjectId("5e1e6381044582129844ffc3"),
"name" : "Coca Cola 2 Litros",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 21.42,
"validFrom" : ISODate("1970-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
},
{
"_id" : ObjectId("5e1e662f044582129844ffda"),
"name" : "Cerveja Heineken Lata 350ml",
"description" : "Cerveja Heineken Lata 350ml",
"quantityAvailable" : 0,
"image" : "volkswagen-polo.jpg",
"price" : 1.55,
"validFrom" : ISODate("2020-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
}
]
},
{
"_id" : ObjectId("5e20e8de9c05f229a484ea27"),
"name" : "Esfihas",
"products" : [
{
"_id" : ObjectId("5e20e8de9c05f229a484ea28"),
"name" : "Esfiha de carne",
"description" : "Esfiha de carne",
"quantityAvailable" : 0,
"image" : "",
"price" : 5,
"validFrom" : ISODate("2020-01-01T00:00:00Z"),
"validTo" : null,
"enabled" : true
}
]
}
],
"__v" : 0
}
{
"_id" : ObjectId("5e0ffd23991918424c8d7c3b"),
"name" : "Pizza Ruth",
"active" : true,
"users" : [ ],
"socialMedias" : [ ],
"branches" : [ ],
"sections" : [ ],
"__v" : 0
}
{
"_id" : ObjectId("5e0ffd3d991918424c8d7c3c"),
"name" : "Feijão de Corda",
"active" : true,
"users" : [ ],
"socialMedias" : [ ],
"branches" : [ ],
"sections" : [ ],
"__v" : 0
}
The fields validFrom and validTo (Date fields) from the collection products nested in branches.sections need to be converted to the format yyyy-mm-dd. I can do that with this aggregation pipeline:
{ $unwind: { path: "$branches.sections", preserveNullAndEmptyArrays: true } },
{
"$addFields": {
"branches.sections.products": {
$map: {
input: "$branches.sections.products",
as: "product",
in: {
'_id': "$$product._id",
'name': "$$product.name",
'description': "$$product.description",
'quantityAvailable': "$$product.quantityAvailable",
'image': "$$product.image",
'imageUrl': "$$product.imageUrl",
'price': "$$product.price",
'validFrom' : {"$dateToString": { "date": "$$product.validFrom", "format": "%Y-%d-%m" }},
'validTo' : {"$dateToString": { "date": "$$product.validTo", "format": "%Y-%d-%m" }},
'enabled': "$$product.enabled",
}
}
}
}
}
I can successfully convert those date fields, but I need now to "re-unwind" the array products, in order to be just like before the unwind.
Any clue in how to proceed? Or even a different way to format those dates without having to unwind? Tried dozens of ways of $group, but without any success.
You just need to $map over each nested array to drill upload the validTo and validFrom field
.aggregate([
{ "$addFields": {
"branches": {
"$map": {
"input": "$branches",
"as": "branch",
"in": {
"$mergeObjects": [
"$$branch",
{ "section": {
"$map": {
"input": "$$branch.sections",
"as": "section",
"in": {
"$mergeObjects": [
"$$section",
{ "product": {
"$map": {
"input": "$$section.products",
"as": "product",
"in": {
"$mergeObjects": [
"$$product",
{
"validFrom": { "$dateToString": { "date": "$$product.validFrom", "format": "%Y-%d-%m" }},
"validTo": { "$dateToString": { "date": "$$product.validTo", "format": "%Y-%d-%m" }}
}
]
}
}
}}
]
}
}
}}
]
}
}
}
}}
])
MongoPlayground

Mongo db query for multiple conditions

I have a Mongodb Json which look like this
{
"_id" : "5b862ebecebe455a1744",
"userId" : "111",
"courses" : [
{
"stateName" : "statge 1",
"courseId" : "1453",
"courseName" : "Program Training 1",
"duration" : 1,
"lag" : 0,
"courseType" : "1",
"transitionType" : "onComplete",
"scheduledStartDate" : ISODate("2018-07-27T16:23:14.000+05:30"),
"scheduledEndDate" : ISODate("2018-07-27T16:23:14.000+05:30"),
"courseProgress" : 0,
"ASD" : ISODate("2018-09-17T23:18:30.636+05:30"),
"score" : 0
},
{
"stateName" : "stage 2",
"courseId" : "1454",
"courseName" : "Program Assessment 1",
"duration" : 1,
"lag" : 0,
"courseType" : "2",
"transitionType" : "onComplete",
"scheduledStartDate" : ISODate("2018-07-28T16:23:14.000+05:30"),
"scheduledEndDate" : ISODate("2018-07-28T16:23:14.000+05:30"),
"courseProgress" : 0,
"score" : 0
},
{
"stateName" : "stage 3",
"courseId" : "911",
"courseName" : "Program Training 3",
"duration" : 1,
"lag" : 0,
"courseType" : "1",
"transitionType" : "onComplete",
"scheduledStartDate" : ISODate("2018-07-29T16:23:14.000+05:30"),
"scheduledEndDate" : ISODate("2018-07-29T16:23:14.000+05:30"),
"courseProgress" : 0,
"score" : 0
}
],
"userStatus" : 1,
"modified" : ISODate("2018-09-12T11:49:47.400+05:30"),
"created" : ISODate("2018-09-12T11:49:47.400+05:30"),
"completionStatus" : "IP",
"currentState" : {
"courseProgress" : 0,
"stateName" : "statge 1",
"courseId" : "1453",
"courseName" : "Program Training 1"
}
}
I want to find a query where condition is. Please help, as I am new to mongodb
courses.transitionType = oncomplete
(PROGRESS<100||(PROGRESS==100&&ASD exists false))
And print Result something like this which contain these below data
{
"_id" : "5b862ebecebe455a1744",
"courseData" : {
"userId" : "4688",
"courseId" : "1476",
"courseProgress" : 0
}
}
You will have to use an aggregation with a $match stage and a $project to format your result.
The tricky part of your request is that you want an answer by course, but 1 item of your collection contains many courses. So first, you can use the $unwind stage to separate every course
db.[CollectionName].aggregate([
{
$unwind : '$courses'
}
{
$match: {
'courses.transitionType': 'onComplete',
$or: [
{
'courses.courseProgress': { $lt: 100 }
},
{
'courses.courseProgress': 100,
ASD: { $exists: 0 }
}
]
}
},
{
$project: {
_id: '0',
courseData: {
userId: '$courses.userId',
courseId: '$courses.courseId',
courseProgress: '$courses.courseProgress'
}
}

Grouping in MongoDB Aggregate

I am starting with MongoDB and i find the Aggregate function hard to understand.
i have read many topics and tried many things, however i still don't get the results i am looking for.
I would like to group some things together to make a overview of the amount of things based on a few match parameters.
my DB:
{
"_id" : ObjectId("5943a4f015813165b6d2b79a"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "99",
"sublocation" : "02",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 2 */
{
"_id" : ObjectId("5943a4f915813165b6d2b79c"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "99",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 3 */
{
"_id" : ObjectId("5943a4fe15813165b6d2b79e"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "25",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 4 */
{
"_id" : ObjectId("5943a56d15813165b6d2b7a0"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "99",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 5 */
{
"_id" : ObjectId("5943a971a367b069bb3e863c"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "98",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 6 */
{
"_id" : ObjectId("5943d824900fce1821c5845d"),
"productType" : "keychain",
"productAmount" : 1,
"orderid" : "1497607251",
"location" : "25",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z")
}
/* 7 */
{
"_id" : ObjectId("5943d9ea900fce1821c5845e"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607251",
"location" : "25",
"sublocation" : "02",
"date" : ISODate("2017-01-01T09:01:13.000Z")
}
my current query:
db.getCollection('products').aggregate([
{ $group: {
_id : {
"orderid" : "$orderid",
"location" : "$location",
"product" : "$productType",
"sublocation" : "$sublocation",
"date" : "$date",
"aant" : { "$sum" : "$productAmount"}
},
"aantal" : { "$sum" : 1},
"aantal2" : { "$sum" : "$productAmount"}
}
},
{
$group : {
_id : "$_id.product",
"productType" : {
"$push" : {
"loc" : "$_id.location",
"prodtype": "$_id.product",
"count": "$aantal2"},
},
"cnt": {"$sum" : "$aantal2"}
}
}
])
i would like to have this result:
{
Location: 25,
sublocation: 01,
<productTypeX> : <count the number of these products>,
<productTypeY> : <count the number of these products>,
<productTypeZ> : <count the number of these products>
},
{
Location: 25,
sublocation: 02,
<productTypeX> : <count the number of these products>,
<productTypeY> : <count the number of these products>,
<productTypeZ> : <count the number of these products>
}
or:
{
location: 25,
sublocation: 01,
products: [
{
<productTypeX> : <count>,
<productTypeY> : <count>,
<productTypeZ> : <count>
}
},
{
location: 25,
sublocation: 02
products: [
{
<productTypeX> : <count>,
<productTypeY> : <count>,
<productTypeZ> : <count>
}
}
if i get this to work i need to convert it to mongoose for NodeJS (tips are welcome)
Thanks in advance!

Mongodb native query and equivalent java code

JSON DO
{
"_id" : "t6Y596WHx44S",
"pos_txn_type" : "CREDIT_AUTHORIZATION",
"pos_payment_method" : "CREDIT_CARD",
"processing_status" : "APPROVED",
"route" : NumberInt(7),
"audit_info" : {
"version" : "1.0.0.0",
"created_on" : ISODate("2016-08-08T07:26:57.000+0000"),
"updated_on" : ISODate("2016-08-08T07:26:57.000+0000")
},
"inflight_transactions" : [
{
"message_exchange" : {
"service_type" : "GATEWAY_SERVICE",
"adapter_id" : "adpIsoUms",
"route1" : NumberInt(7),
"request" : {
"type" : "com.renovite.ripps.kernel.msg.GatewayRequest",
"acquirer_inst_id" : "00000000001",
"host_address" : "127.0.0.1:2000",
"client_address" : "127.0.0.1:58577",
"domain_request" : {
"type" : "com.renovite.ripps.kernel.msg.CardRequestMessage",
"card" : {
"masked_pan" : "411111xxxxx1111",
"card_type" : "VISA"
},
"transactionAmount" : {
"amount" : NumberInt(100),
"amount_type" : "TXN_AMOUNT",
"currency" : "USD",
"currency_iso" : "840",
"currency_minor_unit" : NumberInt(2)
},
"additionalAmountMap" : {
},
"pos" : {
"stan" : "470641215751",
"entry_mode" : "SWIPED",
"pos_environment" : "ATTENDED",
"card_holder_verification_method" : "UNKNOWN",
"pos_card_holder_verification_method" : "MANUAL_SIGNATURE",
"terminal_capability" : "MSR_MANUAL",
"pos_terminal_id" : "0000000000000001",
"pos_transaction_time" : ISODate("2016-08-08T07:26:55.000+0000"),
"pos_transaction_date" : ISODate("2016-08-08T07:26:55.000+0000"),
"pos_function_code" : "100",
"cp" : true
},
"billTo" : {
"postal_code" : "94538"
}
},
"merchant_details" : {
"merchant_code" : "00000000001",
"merchant_category_code" : "5965",
"merchant_postal_code" : "4567",
"device_code" : "0000000000000001"
},
"auditInfo" : {
"version" : "1.0.0.0",
"created_on" : ISODate("2016-08-08T07:26:57.000+0000")
},
"additionalAttributes" : {
},
"raw_header" : "ISO.UMS.03",
"retrival_reference_number" : "000001215751"
},
"response" : {
"type" : "com.renovite.ripps.kernel.msg.GatewayResponse",
"auditInfo" : {
"version" : "1.0.0.0",
"created_on" : ISODate("2016-08-08T07:27:01.000+0000")
},
"additionalAttributes" : {
},
"domain_response" : {
"type" : "com.renovite.ripps.kernel.msg.CardResponseMessage",
"auth_code" : "831000",
"amount" : 9601.0,
"currency" : "USD",
"transaction_time" : ISODate("2016-08-08T01:57:00.000+0000"),
"processor_ref_number" : "4706412203976900504007",
"approval_code" : "0000",
"avs_response_code" : "2",
"reconciliation_id" : "4706412203976900504007",
"partial_auth" : false
}
}
}
},
{
"message_exchange" : {
"service_type" : "FRAUD_SERVICE",
"adapter_id" : "cartFRAUD",
"request" : {
"type" : "com.renovite.ripps.kernel.msg.ProviderRequest",
"auditInfo" : {
"version" : "1.0.0.0",
"created_on" : ISODate("2016-08-08T07:26:58.000+0000")
},
"additionalAttributes" : {
"MerchantTransactionIdentifier" : "t6Y596WHx44S"
},
"retrivalReferenceNumber" : "000001215751",
"merchantDetails" : {
"merchant_code" : "00000000001",
"merchant_category_code" : "5965",
"partial_auth" : "Y"
},
"domain_request" : {
"type" : "com.renovite.ripps.kernel.msg.fraud.FraudRequestMessage",
"client_address" : "127.0.0.1:58577"
}
},
"route" : "6",
"processing_status" : "APPROVED",
"response" : {
"type" : "com.renovite.ripps.kernel.msg.ProviderResponse",
"domain_response" : {
"type" : "com.renovite.ripps.kernel.msg.fraud.FraudResponseMessage",
"fraud_score" : NumberInt(22)
},
"auditInfo" : {
"version" : "1.0.0.0",
"created_on" : ISODate("2016-08-08T07:26:58.000+0000")
},
"additionalAttributes" : {
}
}
}
},
{
"message_exchange" : {
"service_type" : "AUTH_SERVICE",
"adapter_id" : "cartVACP",
"request" : {
"type" : "com.renovite.ripps.kernel.msg.ProviderRequest",
"auditInfo" : {
"version" : "1.0.0.0",
"created_on" : ISODate("2016-08-08T07:26:58.000+0000")
},
"additionalAttributes" : {
"COMMERCEINDICATOR" : "retail",
"MerchantTransactionIdentifier" : "t6Y596WHx44S",
"ThirdPartyCertificationNumber" : "575357012698"
},
"retrivalReferenceNumber" : "000001215751",
"merchantDetails" : {
"merchant_code" : "00000000004",
"merchant_category_code" : "5965",
"partial_auth" : "Y"
},
"domain_request" : {
"type" : "com.renovite.ripps.kernel.msg.CardRequestMessage",
"card" : {
"masked_pan" : "411111xxxxx1111",
"card_type" : "VISA"
},
"transactionAmount" : {
"amount" : 9601.0,
"amount_type" : "TXN_AMOUNT",
"currency" : "USD",
"currency_iso" : "840",
"currency_minor_unit" : NumberInt(2)
},
"additionalAmountMap" : {
},
"pos" : {
"entry_mode" : "SWIPED",
"pos_terminal_id" : "0000000087654321",
"cp" : true
},
"billTo" : {
"postal_code" : "94538"
}
},
"merchant_code" : "v5p234p575357"
},
"route" : "3",
"processing_status" : "APPROVED",
"response" : {
"type" : "com.renovite.ripps.kernel.msg.ProviderResponse",
"status" : "ACCEPT",
"domain_response" : {
"type" : "com.renovite.ripps.kernel.msg.CardResponseMessage",
"auth_code" : "831000",
"amount" : 9601.0,
"currency" : "USD",
"transaction_time" : ISODate("2016-08-08T01:57:00.000+0000"),
"processor_ref_number" : "4706412203976900504007",
"approval_code" : "100",
"avs_response_code" : "2",
"reconciliation_id" : "4706412203976900504007",
"partial_auth" : false
},
"auditInfo" : {
"version" : "1.0.0.0",
"created_on" : ISODate("2016-08-08T07:27:01.000+0000")
},
"additionalAttributes" : {
"PYMT_NETWORK_TXN_ID" : "016153570198200",
"RECEIPT_NUMBER" : "138115",
"REQUEST_TOKEN" : "Ahj/7wSR/kUuB8C84NOOelmjdg2aMWTJgzct2zlgwasGjBg3S36RRSYgFLfpFFJi0gp1MyMJsMmkmW6QHhMgQJyP8ilwPgXnBpxwvBkj",
"REASONCODE" : NumberInt(100),
"PROCESSORRESPONSE" : "00",
"CARDCATEGORY" : "A",
"MERCHANTREFERENCECODE" : "000001215751",
"CARDGROUP" : "0"
}
}
}
},
{
"message_exchange" : {
"service_type" : "LOYALTY_SERVICE",
"adapter_id" : "cartLOYALTY",
"request" : {
"type" : "com.renovite.ripps.kernel.msg.ProviderRequest",
"auditInfo" : {
"version" : "1.0.0.0",
"created_on" : ISODate("2016-08-08T07:27:01.000+0000")
},
"additionalAttributes" : {
"MerchantTransactionIdentifier" : "t6Y596WHx44S"
},
"retrivalReferenceNumber" : "000001215751",
"merchantDetails" : {
"merchant_code" : "00000000001",
"merchant_category_code" : "5965",
"partial_auth" : "Y"
},
"domain_request" : {
"type" : "com.renovite.ripps.kernel.msg.loyalty.LoyaltyRequestMessage",
"amount" : 9601.0,
"client_address" : "127.0.0.1:58577"
}
},
"route" : "7",
"processing_status" : "APPROVED",
"response" : {
"type" : "com.renovite.ripps.kernel.msg.ProviderResponse",
"domain_response" : {
"type" : "com.renovite.ripps.kernel.msg.loyalty.LoyaltyResponseMessage",
"loyaltyPoint" : NumberInt(677)
},
"auditInfo" : {
"version" : "1.0.0.0",
"created_on" : ISODate("2016-08-08T07:27:01.000+0000")
},
"additionalAttributes" : {
}
}
}
}
]
}
Below is the native mongo query -
db.txnlog.aggregate([
{
$group : {_id : "$pos_txn_type", count : {$sum : 1}, route_sum : {$push : "$inflight_transactions.0.message_exchange.request.domain_request.transactionAmount.amount"}}
}
])
and sheel output-
{ "_id" : "RECONCILE_REQUEST", "count" : 9, "route_sum" : [ [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ] ] }
{ "_id" : "CREDIT_CAPTURE", "count" : 2, "route_sum" : [ [ ], [ ] ] }
{ "_id" : "CREDIT_AUTHORIZATION", "count" : 2, "route_sum" : [ [ ], [ ] ] }
Problem i am not getting amount sum ? Please provide some input.
You can not use the dot notation to access an array element on the group stage, you have to add an extra $project stage to $slice the inflight_transactions array. Here is the query:
db.txnlog.aggregate([
{$project: {
pos_txn_type: 1,
inflight_transaction: {$slice: ["$inflight_transactions", 1]}
}},
{$group: {_id: "$pos_txn_type",
count: {$sum: 1},
route_sum: {$push: "$inflight_transaction.message_exchange.request.domain_request.transactionAmount.amount"}
}
}
]);
// output
{ "_id" : "CREDIT_AUTHORIZATION", "count" : 1, "route_sum" : [ [ 100 ] ] }

Only return inner element from nested array in Mongo

I currently have a collection that contains documents like this
{
"_id" : "sHXFGyTkZBYeZXcax",
"name" : "Sunless Sunday",
"description" : "blabla",
"game_id" : "qPrZBahQLHQXabwuv",
"date_checkin" : ISODate("2015-11-07T01:01:00.000Z"),
"date_start" : ISODate("2015-11-12T00:04:00.000Z"),
"date_end" : ISODate("2015-11-19T00:05:00.000Z"),
"company_id" : 1,
"featured" : 1,
"premium" : 0,
"type" : 0,
"ongoing" : 1,
"prizes" : [
{
"place" : 1,
"amount" : 18
},
{
"place" : 2,
"amount" : 2
}
],
"createdAt" : ISODate("2015-11-05T22:34:01.494Z"),
"modifiedAt" : ISODate("2015-11-05T22:34:01.494Z"),
"owner" : "CLEopD9HRAeE9eiXW",
"players" : [
{
"player_id" : "WdLK9aaRgdPnYsw8B",
"status" : 2
},
{
"player_id" : "vF6JEwMy9yaRtKuiG",
"status" : 1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"status" : -1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"status" : -1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"status" : -1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"status" : -1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"status" : -1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"status" : -1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"status" : -1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"status" : 1
}
],
"rounds" : [
{
"roundNumber" : 1,
"participants" : [],
"matchesToWin" : 3,
"matches" : [
{
"matchNumber" : 1,
"party1" : "WdLK9aaRgdPnYsw8B"
}
]
},
{
"roundNumber" : 2,
"participants" : [
{
"player_id" : "WdLK9aaRgdPnYsw8B",
"status" : 2
},
{
"player_id" : "vF6JEwMy9yaRtKuiG",
"status" : 1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"status" : 1
}
],
"matchesToWin" : 2,
"matches" : [
{
"matchNumber" : 1,
"players" : [
{
"party" : 1
},
{
"player_id" : "WdLK9aaRgdPnYsw8B",
"party" : 2
}
],
"party1" : "freewin",
"party2" : "WdLK9aaRgdPnYsw8B",
"currentGame" : 1,
"winner" : "WdLK9aaRgdPnYsw8B",
"matchFinished" : ISODate("2015-11-16T16:25:37.712Z")
},
{
"matchNumber" : 2,
"players" : [
{
"player_id" : "vF6JEwMy9yaRtKuiG",
"party" : 1
},
{
"player_id" : "KD4s2E3AezhFcQDCd",
"party" : 2
}
],
"party1" : "vF6JEwMy9yaRtKuiG",
"party2" : "KD4s2E3AezhFcQDCd",
"score1" : 0,
"score2" : 0,
"currentGame" : 1
}
]
}
]
}
Now I'm trying to see if a certain player has an active match. So this means that the the player would be either party1 or party2 in a match that has no winner at the moment.
I currently have this query
activeMatch = Tournaments.find({
'ongoing': 1,
'rounds.matches': {
$elemMatch: {
$or: [
{ 'party1': player[0]._id },
{ 'party2': player[0]._id },
],
winner: { $exists: false }
}
}
},
{ "rounds.matches.$": 1 }
);
I have 2 problems at the moment:
My query returns the round it matched, but it does not filter for the match it matched. So I effectively only get round with roundNumber = 2, but from that round I get every match, where as I would only be interested in a specific match.
The filtering only happens when I execute my query through the shell. When I use it in my .jsx file and console.log the result to the client, I see ALL rounds.
Any help?