Compare two values in document and display the common values in each row in result - mongodb

I have documents in which am storing two main objects scan and result, I want the output such that in result I get separate row for each match of scan.location and result.location.
Date:
{
"_id" : ObjectId("6024d02a1bf5152b44baf521"),
"scan" : {
"customerId" : "e2565eac-2086-48fc-ba18-dbce74602e22",
"customerGenderSelection" : "F",
"scanQuery" : {
"service" : "MA",
"date" : "08-Nov-2020",
"locations" : [
{
"locationId" : "0023",
"locationName" : "dobson"
},
{
"locationId" : "0001",
"locationName" : "shea"
}
]
},
"sessionId" : "70511849-97f8-4318-a96e-bb3a573c52ea",
},
"result" : [
{
"employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time" : "11:00",
"locationId" : "0023"
},
{
"employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time" : "12:00",
"locationId" : "0023"
},
{
"employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time" : "12:30",
"locationId" : "0023"
},
{
"employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time" : "13:00",
"locationId" : "0001"
}
]
}
I want result where scan.scanQuery.locations.locationId == result.locationId. So expecting a result in the below format:
Expected Response:
{
"scan" : {
"customerId" : "e2565eac-2086-48fc-ba18-dbce74602e22",
"customerGenderSelection" : "F",
"scanQuery" : {
"service" : "MA",
"date" : "08-Nov-2020",
"locations" : [
{
"locationId" : "0023",
"locationName" : "dobson"
}
]
},
"sessionId" : "70511849-97f8-4318-a96e-bb3a573c52ea",
},
"result" : [
{
"employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time" : "11:00",
"locationId" : "0023"
},
{
"employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time" : "12:00",
"locationId" : "0023"
},
{
"employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time" : "12:30",
"locationId" : "0023"
}
]
},
{
"scan" : {
"customerId" : "e2565eac-2086-48fc-ba18-dbce74602e22",
"customerGenderSelection" : "F",
"scanQuery" : {
"service" : "MA",
"date" : "08-Nov-2020",
"locations" :
{
"locationId" : "0001",
"locationName" : "shea"
}
]
},
"sessionId" : "70511849-97f8-4318-a96e-bb3a573c52ea",
},
"result" : [
{
"employeeId" : "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time" : "13:00",
"locationId" : "0001"
}
]
}
Any suggestions or ideas would be helpful.

Try this:
db.locations.aggregate([
{
$unwind: "$scan.scanQuery.locations"
},
{
$addFields: {
result: {
$filter: {
input: "$result",
as: "item",
cond: {
$eq: ["$scan.scanQuery.locations.locationId", "$$item.locationId"]
}
}
}
}
}
]);
Output:
{
"_id": ObjectId("6024d02a1bf5152b44baf521"),
"scan": {
"customerId": "e2565eac-2086-48fc-ba18-dbce74602e22",
"customerGenderSelection": "F",
"scanQuery": {
"service": "MA",
"date": "08-Nov-2020",
"locations": {
"locationId": "0023",
"locationName": "dobson"
}
},
"sessionId": "70511849-97f8-4318-a96e-bb3a573c52ea"
},
"result": [
{
"employeeId": "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time": "11:00",
"locationId": "0023"
},
{
"employeeId": "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time": "12:00",
"locationId": "0023"
},
{
"employeeId": "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time": "12:30",
"locationId": "0023"
}
]
},
{
"_id": ObjectId("6024d02a1bf5152b44baf521"),
"scan": {
"customerId": "e2565eac-2086-48fc-ba18-dbce74602e22",
"customerGenderSelection": "F",
"scanQuery": {
"service": "MA",
"date": "08-Nov-2020",
"locations": {
"locationId": "0001",
"locationName": "shea"
}
},
"sessionId": "70511849-97f8-4318-a96e-bb3a573c52ea"
},
"result": [
{
"employeeId": "224f55b2-27bc-4e34-8249-a8d201540ac2",
"time": "13:00",
"locationId": "0001"
}
]
}

Related

I want to search product by pName and pCode with regex,and return only selected values of product array

{ "_id" : ObjectId("614ace4398294e981cc69053"), "storeId" : ObjectId("614acd4898294e981cc69046"), "product" : [ { "count" : 120, "pCode" : "KL", "pName" : "hat", "pPrice" : 350, "_id" : ObjectId("6151687aa1114528f506d76d") }, { "count" : 500, "pCode" : "J", "pName" : "jeans", "pPrice" : 850, "_id" : ObjectId("6151687aa1114528f506d76e") } ], "createdAt" : ISODate("2021-09-22T06:33:39.422Z"), "updatedAt" : ISODate("2021-10-06T04:54:56.817Z"), "__v" : 0, "status" : true }
{ "_id" : ObjectId("614b23d0b50f800cf624b0d7"), "storeId" : ObjectId("614acd4898294e981cc69046"), "product" : [ { "count" : 25, "pCode" : "LJ", "pName" : "ladies jeans", "pPrice" : 350, "_id" : ObjectId("614b23d0b50f800cf624b0d8") }, { "count" : 40, "pCode" : "NW", "pName" : "night wear", "pPrice" : 900, "_id" : ObjectId("614b23d0b50f800cf624b0d9") } ], "createdAt" : ISODate("2021-09-22T12:38:40.059Z"), "updatedAt" : ISODate("2021-09-30T12:06:09.727Z"), "__v" : 0, "status" : true }
You can use $regexMatch into $filter like this:
db.collection.aggregate([
{
"$project": {
"_id": 1,
"storeId": 1,
"status": 1,
"createdAt": 1,
"updatedAt": 1,
"product": {
"$filter": {
"input": "$product",
"as": "p",
"cond": {
"$and": [
{
"$regexMatch": {
"input": "$$p.pCode",
"regex": "J",
"options": "i"
}
},
{
"$regexMatch": {
"input": "$$p.pName",
"regex": "jea",
"options": "i"
}
}
]
}
}
}
}
}
])
Example here

MongoDB Query that will $project document values in horizontal format

Im trying to create a query that will project or show the field in HORIZONTAL format. Below is my sample collection and the expected output. BTW, Im also using jaspersoft studio to create the report but i think my output should be done in mongodb query. Hope someone can help. Thanks!
"_id" : ObjectId("60ddc6f44c893c117141e9b9"),
"observationvalues" : [
{
"_id" : ObjectId("60ddc6f44c893c117141e9c3"),
"name" : "Systolic BP",
"resultvalue" : "88.00"
},
{
"_id" : ObjectId("60ddc6f44c893c117141e9c2"),
"name" : "Diastolic BP",
"resultvalue" : "66.00"
},
{
"_id" : ObjectId("60ddc6f44c893c117141e9c1"),
"name" : "Weight",
"resultvalue" : "90.00"
},
{
"_id" : ObjectId("60ddc6f44c893c117141e9c5"),
"name" : "Height",
"resultvalue" : null
}
],
"createdat" : ISODate("2021-07-01T13:45:24.679Z"),
"modifiedat" : ISODate("2021-07-01T13:45:24.679Z"),
"statusflag" : "A"
"_id" : ObjectId("60ddc6f44c893c117141e8b8"),
"observationvalues" : [
{
"_id" : ObjectId("60ddc6f44c893c117141e9b3"),
"name" : "Systolic BP",
"resultvalue" : "84.00"
},
{
"_id" : ObjectId("60ddc6f44c893c117141e9b2"),
"name" : "Diastolic BP",
"resultvalue" : "63.00"
},
{
"_id" : ObjectId("60ddc6f44c893c117141e9b1"),
"name" : "Weight",
"resultvalue" : "99.00"
},
{
"_id" : ObjectId("60ddc6f44c893c117141e9b5"),
"name" : "Height",
"resultvalue" : 172.00
}
],
"createdat" : ISODate("2021-07-02T13:45:24.679Z"),
"modifiedat" : ISODate("2021-07-02T13:45:24.679Z"),
"statusflag" : "A"
"_id" : ObjectId("60ddc6f44c893c117141e7b7"),
"observationvalues" : [
{
"_id" : ObjectId("60ddc6f44c893c117141e9a3"),
"name" : "Systolic BP",
"resultvalue" : "81.00"
},
{
"_id" : ObjectId("60ddc6f44c893c117141e9a2"),
"name" : "Diastolic BP",
"resultvalue" : "65.00"
},
{
"_id" : ObjectId("60ddc6f44c893c117141e9a1"),
"name" : "Weight",
"resultvalue" : "96.00"
},
{
"_id" : ObjectId("60ddc6f44c893c117141e9a5"),
"name" : "Height",
"resultvalue" : 165.00
}
],
"createdat" : ISODate("2021-07-03T13:45:24.679Z"),
"modifiedat" : ISODate("2021-07-03T13:45:24.679Z"),
"statusflag" : "A",
The expected Output will be:
{"createdat" : "2021-07-01T13:45:24.679Z", "Systolic BP" : 88.00 ,"Diastolic BP" : 66.00 ,"Weight": 90.00 ,"Height":null }
{"createdat" : "2021-07-01T13:45:24.679Z", "Systolic BP" : 84.00 ,"Diastolic BP" : 63.00 ,"Weight": 99.00 ,"Height":172.00 }
{"createdat" : "2021-07-03T13:45:24.679Z", "Systolic BP" : 81.00 ,"Diastolic BP" : 65.00 ,"Weight": 96.00 ,"Height":165.00 }
I have created my query but it is not having the output in one line grouped for each createdat field
{
$project : {
_id: {
"systolic": {"$cond": [ { "$eq": ["$name","Systolic BP" ] }, "$resultvalue","" ] },
"diastolic": {"$cond": [ { "$eq": ["$name","Diastolic BP" ] }, "$resultvalue","" ] },
"weight": {"$cond": [ { "$eq": ["$name","Weight" ] }, "$resultvalue","" ] },
"height": {"$cond": [ { "$eq": ["$name","Height" ] }, "$resultvalue","" ] },
"create": "$createdat"
}
}
},
Your expected data output could be done like this: playground
[
{
"$project": {
"createdat": 1,
"rows": {
"$arrayToObject": {
"$map": {
"input": "$observationvalues",
"in": {
"k": "$$this.name",
"v": {
"$convert": {
"input": "$$this.resultvalue",
"to": "double",
"onError": null,
"onNull": null
}
}
}
}
}
}
}
},
{
"$addFields": {
"rows.create": "$createdat"
}
},
{
"$replaceRoot": {
"newRoot": "$rows"
}
},
{
"$match": {
"Systolic BP": 84.00
}
}
]
To get them in one line you should look for some JSON formater.

$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

MongoDB Use $group for the subset after $group

I just learned mongoDB, I am trying to find some repeat customer info through my customer database.
The sample collection:
{
"_id" : ObjectId("5b7617e48146d8bae"),
"amazon_id" : "112",
"date" : "2018-01-25T18:40:55-08:00",
"email" : "xxxxx#marketplace.amazon.com",
"buy_name" : "xxxxx",
"sku" : "NPC-50",
"qty" : 8,
"price" : 215.92,
"reci_name" : "XXXXX",
"street1" : "XXXXX",
"street2" : "",
"street3" : "",
"city" : "XXXXX",
"state" : "XXXXX",
"zip_code" : "XXXXXX"
}
{
"_id" : ObjectId("5b761712e48146d8bae"),
"amazon_id" : "114",
"date" : "2018-01-27T18:40:55-08:00",
"email" : "xxxxx#marketplace.amazon.com",
"buy_name" : "xxxxx",
"sku" : "ABC",
"qty" : 1,
"price" : 19.99,
"reci_name" : "XXXXX",
"street1" : "XXXXX",
"street2" : "",
"street3" : "",
"city" : "XXXXX",
"state" : "XXXXX",
"zip_code" : "XXXXXX"
}
I group all customer info by their email id, and here is my code:
db.getCollection('order').aggregate([
{ $group: { _id: "$email",
OrderInfo: {$push: {orderId: "$amazon_id", sku: "$sku", qty: "$qty", price:"$price"
}},
CustomerInfo: {$addToSet: {buyName: "$buy_name",reName: "$reci_name", email: "$email", street1: "$street1",
street2: "$street2", city: "$city", state: "$state", zipCode: "$zip_code"} }
}},
{ $project: {_id: 1, OrderInfo: 1, CustomerInfo:1, total_price:{$sum: "$OrderInfo.price"} }},
{ $match: {total_price: {$gt:100} } },
{ $sort: {total_price:-1}},
], { allowDiskUse: true } );
It shows me the result:
{
"_id" : "xxxxxxx#marketplace.amazon.com",
"OrderInfo" : [
{
"orderId" : "112",
"sku" : "NPC-50",
"qty" : 8,
"price" : 215.92
},
{
"orderId" : "112",
"sku" : "NPC-50",
"qty" : 1,
"price" : 26.99
},
{
"orderId" : "114",
"sku" : "NPC-50",
"qty" : 1,
"price" : 26.99
},
{
"orderId" : "114",
"sku" : "ABC",
"qty" : 1,
"price" : 19.99
},
{
"orderId" : "116",
"sku" : "ABC",
"qty" : 1,
"price" : 19.99
},
],
"CustomerInfo" : [
{
"buyName" : "xxxxxxxxx",
"reName" : "xxxxxxxxxxxx",
"email" : "xxxxxxxxxxxx#marketplace.amazon.com",
"street1" : "xxxxxxxxxxx",
"street2" : "",
"city" : "xxxxxxxxxx",
"state" : "xxxxxxxxxxxx",
"zipCode" : "xxxxxxxxxx"
},
{
"buyName" : "xxxxxxxxxx",
"reName" : "xxxxxx",
"email" : "xxxxxxxx#marketplace.amazon.com",
"street1" : "xxxxxxxxxxx",
"street2" : "",
"city" : "xxxxx",
"state" : "xxxx",
"zipCode" : "xxxxxxxx"
}
],
"total_price" : 309.88
}
However, I want to group the sku and sum up the qty and price in the OrderInfo Set. My expected output is something like:
{
"OrderInfo" : [
{
"sku": "NPC-50",
"qty": 10,
"price": 269.9
},
{
"sku": "ABC",
"qty": 2,
"price": 39.98
},
],
"CustomerInfo" : [
{
"buyName" : "xxxxxxxxx",
"reName" : "xxxxxxxxxxxx",
"email" : "xxxxxxxxxxxx#marketplace.amazon.com",
"street1" : "xxxxxxxxxxx",
"street2" : "",
"city" : "xxxxxxxxxx",
"state" : "xxxxxxxxxxxx",
"zipCode" : "xxxxxxxxxx"
},
{
"buyName" : "xxxxxxxxxx",
"reName" : "xxxxxx",
"email" : "xxxxxxxx#marketplace.amazon.com",
"street1" : "xxxxxxxxxxx",
"street2" : "",
"city" : "xxxxx",
"state" : "xxxx",
"zipCode" : "xxxxxxxx"
}
],
"total_price" : 309.88
}
Any Help will be appreciated.
You can use below aggregation.
db.order.aggregate([
{"$group":{
"_id":{"email":"$email","sku":"$sku"},
"qty":{"$sum":"$qty"},
"price":{"$sum":"$price"},
"CustomerInfo":{
"$addToSet":{
"buyName":"$buy_name",
"reName":"$reci_name",
"email":"$email",
"street1":"$street1",
"street2":"$street2",
"city":"$city",
"state":"$state",
"zipCode":"$zip_code"
}
}
}},
{"$group":{
"_id":"$_id.email",
"OrderInfo":{"$push":{"sku":"$_id.sku","qty":"$qty","price":"$price"}},
"total_price":{"$sum":"$price"},
"CustomerInfo":{"$first":"$CustomerInfo"}
}},
{"$match":{"total_price":{"$gt":100}}},
{"$sort":{"total_price":-1}}
])
You can try below aggregation
db.collection.aggregate([
{ "$group": {
"_id": {
"email": "$email",
"sku": "$sku"
},
"CustomerInfo": {
"$addToSet": {
"buyName": "$buy_name",
"otherFields": "$otherFields",
}
},
"price": { "$sum": "$price" },
"qty": { "$sum": "$qty" }
}},
{ "$group": {
"_id": "$_id.email",
"CustomerInfo": { "$first": "$CustomerInfo" },
"OrderInfo": {
"$push": {
"sku": "$_id.sku",
"qty": "$qty",
"price": "$price"
}
}
}}
])

MongoDB Aggregation

I have a the following collection
{ "data" :[
{ "country" :"USA", "state": "NJ", "County" : "Middlesex", "city" : "Edison", "population" :0923422 },
{ "country" :"USA", "state": "NJ", "County" : "Mercer", "city" : "Princeton", "population" :0923422 },
{ "country" :"USA", "state": "NY", "County" : "Middlesex", "city" : "Edison", "population" :234234 },
{ "country" :"USA", "state": "NY", "County" : "Ocean", "city" : "Albony", "population" :234324 },
{ "country" :"USA", "state": "PA", "County" : "Central", "city" : "Edison", "population" :0923422 },
{ "country" :"USA", "state": "NJ", "County" : "Middlesex", "city" : "Edison", "population" :23432 },
{ "country" :"USA", "state": "OH", "County" : "Middlesex", "city" : "Cincinatti", "population" :0923422 },
{ "country" :"USA", "state": "OH", "County" : "Middlesex", "city" : "Columbos", "population" :23432 } ]
}
looking to find the total population by Country, State, County and City with nested aggregation in mongodb.
Please help with query.
Query:-
db.collection.aggregate([
{$group:
{
_id : {"country" : "$country",
"state" : "$state",
"County" : "$County",
"city" : "$city"
},
"totalPopulationOfCity" : {$sum: "$population" }
}},
{$group:
{
_id : {"country" : "$_id.country",
"state" : "$_id.state",
"County" : "$_id.County"
},
"cities" : { $addToSet: {"city" : "$_id.city", "totalPopulationOfCity" : "$totalPopulationOfCity"} } ,
"totalPopulationOfCounty" : {$sum: "$totalPopulationOfCity" }
}},
{$group:
{
_id : {"country" : "$_id.country",
"state" : "$_id.state"
},
"counties" : {$addToSet: {"County": "$_id.County", "cities" : "$cities",
"totalPopulationOfCounty" : "$totalPopulationOfCounty"} } ,
"totalPopulationOfState" : {$sum: "$totalPopulationOfCounty" }
}},
{$group:
{
_id : {"country" : "$_id.country"
},
"states" : {$addToSet : {"state" : "$_id.state", "counties": "$counties", "totalPopulationOfState" : "$totalPopulationOfState"}},
"totalPopulationOfCountry" : {$sum: "$totalPopulationOfState" }
}},
]);
Output:-
/* 1 */
{
"_id" : {
"country" : "USA"
},
"states" : [
{
"state" : "NY",
"counties" : [
{
"County" : "Ocean",
"cities" : [
{
"city" : "Albony",
"totalPopulationOfCity" : 234324
}
],
"totalPopulationOfCounty" : 234324
},
{
"County" : "Middlesex",
"cities" : [
{
"city" : "Edison",
"totalPopulationOfCity" : 234234
}
],
"totalPopulationOfCounty" : 234234
}
],
"totalPopulationOfState" : 468558
},
{
"state" : "NJ",
"counties" : [
{
"County" : "Mercer",
"cities" : [
{
"city" : "Princeton",
"totalPopulationOfCity" : 923422
}
],
"totalPopulationOfCounty" : 923422
},
{
"County" : "Middlesex",
"cities" : [
{
"city" : "Edison",
"totalPopulationOfCity" : 946854
}
],
"totalPopulationOfCounty" : 946854
}
],
"totalPopulationOfState" : 1870276
},
{
"state" : "OH",
"counties" : [
{
"County" : "Middlesex",
"cities" : [
{
"city" : "Cincinatti",
"totalPopulationOfCity" : 923422
},
{
"city" : "Columbos",
"totalPopulationOfCity" : 23432
}
],
"totalPopulationOfCounty" : 946854
}
],
"totalPopulationOfState" : 946854
},
{
"state" : "PA",
"counties" : [
{
"County" : "Central",
"cities" : [
{
"city" : "Edison",
"totalPopulationOfCity" : 923422
}
],
"totalPopulationOfCounty" : 923422
}
],
"totalPopulationOfState" : 923422
}
],
"totalPopulationOfCountry" : 4209110
}
Verification using excel:-