Get all possible combinations from array in MongoDB aggregation 🚀 - mongodb

How to do aggregation ($group) by the same values ​​from the array? Not all at once, but few or all, if any. I can do $group by one word, but I also need all possible variations...
Collection example:
{"keywords": ["gta", "distribution", "keys"]}
{"keywords": ["gta", "online", "moto", "races"]}
{"keywords": ["gta", "online", "samp"]}
Result example:
"gta" - 3 matches
"online" - 2 matches
"gta online" - 2 matches

You could use $reduce to extract all combinations of pairs from an array. I've started from this post and I've added the current item, $unwind the
initial array and count the items :
db.test.aggregate([
{
$project: {
pairs: {
$reduce: {
input: { $range: [0, { $size: "$keywords" }] },
initialValue: [],
in: {
$concatArrays: [
"$$value",
[[{ $arrayElemAt: ["$keywords", "$$this"] }]],
{
$let: {
vars: { i: "$$this" },
in: {
$map: {
input: { $range: [{ $add: [1, "$$i"] }, { $size: "$keywords" }] },
in: [{ $arrayElemAt: ["$keywords", "$$i"] }, { $arrayElemAt: ["$keywords", "$$this"] }]
}
}
}
}
]
}
}
}
}
}, {
$unwind: "$pairs"
}, {
$group: {
_id: "$pairs",
count: { $sum: 1 }
}
}
])
Output :
{ "_id" : [ "online", "samp" ], "count" : 1 }
{ "_id" : [ "gta", "samp" ], "count" : 1 }
{ "_id" : [ "online", "races" ], "count" : 1 }
{ "_id" : [ "moto", "races" ], "count" : 1 }
{ "_id" : [ "gta", "keys" ], "count" : 1 }
{ "_id" : [ "races" ], "count" : 1 }
{ "_id" : [ "gta", "distribution" ], "count" : 1 }
{ "_id" : [ "samp" ], "count" : 1 }
{ "_id" : [ "distribution", "keys" ], "count" : 1 }
{ "_id" : [ "gta" ], "count" : 3 }
{ "_id" : [ "online" ], "count" : 2 }
{ "_id" : [ "keys" ], "count" : 1 }
{ "_id" : [ "gta", "online" ], "count" : 2 }
{ "_id" : [ "moto" ], "count" : 1 }
{ "_id" : [ "online", "moto" ], "count" : 1 }
{ "_id" : [ "distribution" ], "count" : 1 }
{ "_id" : [ "gta", "moto" ], "count" : 1 }
{ "_id" : [ "gta", "races" ], "count" : 1 }
If you need more combinations, you may need to update the $reduce stage above

Related

mongodb getting an array inside a nested array

I'm still new to mongodb, I have this basic enrollment system data:
{ "_id" : ObjectId("62277d92a561e550d5ec73ca"), "sid" : 1, "sname" : "sad", "semail" : "dsa", "scourse" : "it", "enrolled" : [ { "subjid" : 3 } ] }
{ "_id" : ObjectId("6227875bdbcc41a56a863697"), "sid" : 2, "sname" : "daws", "semail" : "dws", "scourse" : "cs", "enrolled" : [ { "subjid" : 1, "grades" : [ { "prelim" : "A", "midterm" : "B", "prefinal" : "B", "final" : "A" } ] }, { "subjid" : 2, "grades" : [ { "prelim" : "D", "midterm" : "A", "prefinal" : "B", "final" : "F" } ] } ] }
I want display the grades of sid 2 who has enrolled subjid 1.
I tried using this aggregation line:
db.students2.aggregate( [{"$match":{"sid":{"$eq":2},"enrolled.subjid":{"$eq":2}}}, {$group: {_id:'$enrolled.subjid[1]', prelim:{$first:'$enrolled.grades.prelim'},midterm:{$first:'$enrolled.grades.midterm'},prefinal:{$first:'$enrolled.grades.prefinal'},"final":{$first:'$enrolled.grades.final'} } } ])
but this was the result:
{ "_id" : [ ], "prelim" : [ [ "A" ], [ "D" ] ], "midterm" : [ [ "B" ], [ "A" ] ], "prefinal" : [ [ "B" ], [ "B" ] ], "final" : [ [ "A" ], [ "F" ] ] }
I only wanted to get the grades of subjid 1 but it also got the grades of subjid 2
Maybe you need something like this:
db.collection.aggregate([
{
"$match": {
"sid": 2,
"enrolled.subjid": 1
}
},
{
"$addFields": {
"enrolled": {
"$filter": {
"input": "$enrolled",
"as": "en",
"cond": {
$eq: [
"$$en.subjid",
1
]
}
}
}
}
},
{
$unwind: "$enrolled"
},
{
$unwind: "$enrolled.grades"
},
{$limit:1}
,
{
$project: {
_id: "$enrolled.subjid",
prelim: "$enrolled.grades.prelim",
midterm: "$enrolled.grades.midterm",
prefinal: "$enrolled.grades.prefinal",
"final": "$enrolled.grades.final"
}
}
])
Explained:
Match the necessary documents (sid=2,subjid=1)
Filter only the enrolled elements based on subjid ( subjid=1 )
unwind the two array
limit to the first result document available only in case there is more.
project the necesary fields
playground

query for finding average of average stored in mongodb using count of every average

We have data like
{
"_id" : ObjectId("64326493749326499446"),
"dId" : "d_155",
"pId" : "5f4cb595cff47e0001b20882",
"sId" : "825",
"paramName" : "Utility_Air_Flow",
"avg" : 488270.454545455,
"count" : NumberLong(220),
"date" : ISODate("2020-09-03T18:30:00.000Z"),
"dataPerHour" : {
"19" : {
"min" : 8399.0,
"max" : 995990.0,
"avg" : 488270.454545455,
"count" : NumberLong(220),
"values" : [
{
"paramValue" : "90235",
"time" : ISODate("2020-09-04T13:37:07.000Z")
},
{
"paramValue" : "272297",
"time" : ISODate("2020-09-04T13:37:14.000Z")
}
]
},
"20" : {
"min" : 8399.0,
"max" : 995990.0,
"avg" : 488270.454545455,
"count" : NumberLong(220),
"values" : [
{
"paramValue" : "90235",
"time" : ISODate("2020-09-04T13:37:07.000Z")
},
{
"paramValue" : "272297",
"time" : ISODate("2020-09-04T13:37:14.000Z")
}
]
}
},
"_class" : "org.nec.iotplatform.entities.RawData"
}
and we need to find average of all the average of already stored averages inside dataPerHour.
We need to find average of averages according to the formulae:
(average1count1)+(avarege2count2)+
(average3*count3)/(count1+count2+count3)
You can use the following query:
db.collection.aggregate([
{
$project: {
dataPerHour: {
$objectToArray: "$dataPerHour"
}
}
},
{
$project: {
"average": {
"$divide": [
{
$reduce: {
input: "$dataPerHour",
initialValue: 0,
in: {
"$add": [
"$$value",
{
"$multiply": [
"$$this.v.count",
"$$this.v.avg"
]
}
]
}
}
},
{
$reduce: {
input: "$dataPerHour",
initialValue: 0,
in: {
"$add": [
"$$value",
"$$this.v.count"
]
}
}
}
]
}
}
}
])
MongoDB Playground

Mongo 3.6: Removing Duplicates

Using the following command I get all the duplicate values in my collection based on the "no" field:
db.books.aggregate([{ $group: { _id: {no: "$no"}, uniqueIds: {$addToSet: "$_id"}, count: {$sum: 1}}}, { $match: { count: {"$gt": 1}}}, { $sort: {count: -1}}])
This returns the following:
{ "_id" : { "no" : 160541455 }, "uniqueIds" : [ ObjectId("5b3a3a3bd6194c5bfe40a523"), ObjectId("5b3a345dd6194c5bfe3deefa"), ObjectId("5b3a3509d6194c5bfe3e2e29"), ObjectId("5b3a3440d6194c5bfe3de3b4"), ObjectId("5b3a336ad6194c5bfe3d80a9"), ObjectId("5b3a3600d6194c5bfe3eb073"), ObjectId("5b3a37e1d6194c5bfe3f96f0"), ObjectId("5b3a35aed6194c5bfe3e8b83"), ObjectId("5b3a36ead6194c5bfe3f2dbd"), ObjectId("5b3a3ea6d6194c5bfe42d794"), ObjectId("5b3a3731d6194c5bfe3f50d2"), ObjectId("5b3a399bd6194c5bfe40676c") ], "count" : 12 }
{ "_id" : { "no" : 105900593 }, "uniqueIds" : [ ObjectId("5b3a3efad6194c5bfe42fc1f"), ObjectId("5b3a3df3d6194c5bfe429191"), ObjectId("5b3a3697d6194c5bfe3f0ca9"), ObjectId("5b3a385fd6194c5bfe3fdced"), ObjectId("5b3a3b69d6194c5bfe416901"), ObjectId("5b3a347ed6194c5bfe3dfeff"), ObjectId("5b3a335ad6194c5bfe3d7c15"), ObjectId("5b3a3887d6194c5bfe3feaad"), ObjectId("5b3a38b8d6194c5bfe400088"), ObjectId("5b3a358dd6194c5bfe3e81ea"), ObjectId("5b3a3b3fd6194c5bfe4157bc"), ObjectId("5b3a3decd6194c5bfe428efa") ], "count" : 12 }
{ "_id" : { "no" : 144919593 }, "uniqueIds" : [ ObjectId("5b3a3e46d6194c5bfe42b277"), ObjectId("5b3a3c22d6194c5bfe41b05a"), ObjectId("5b3a398cd6194c5bfe4065be"), ObjectId("5b3a37a1d6194c5bfe3f8239"), ObjectId("5b3a3678d6194c5bfe3f0496"), ObjectId("5b3a33d2d6194c5bfe3db42c"), ObjectId("5b3a36e6d6194c5bfe3f2d4d"), ObjectId("5b3a3d05d6194c5bfe421e97"), ObjectId("5b3a384ad6194c5bfe3fd621"), ObjectId("5b3a3565d6194c5bfe3e6c44") ], "count" : 10 }
{ "_id" : { "no" : 86204442 }, "uniqueIds" : [ ObjectId("5b3a3df5d6194c5bfe429204"), ObjectId("5b3a3d1cd6194c5bfe4224a1"), ObjectId("5b3a3b33d6194c5bfe415288"), ObjectId("5b3a3934d6194c5bfe403ed9"), ObjectId("5b3a3c39d6194c5bfe41b664"), ObjectId("5b3a37dbd6194c5bfe3f961c"), ObjectId("5b3a3688d6194c5bfe3f0613"), ObjectId("5b3a3731d6194c5bfe3f50c6"), ObjectId("5b3a37dfd6194c5bfe3f9697") ], "count" : 9 }
{ "_id" : { "no" : 119417424 }, "uniqueIds" : [ ObjectId("5b3a3b34d6194c5bfe4152a5"), ObjectId("5b3a392cd6194c5bfe403b21"), ObjectId("5b3a399ad6194c5bfe406736"), ObjectId("5b3a38b9d6194c5bfe4000c7"), ObjectId("5b3a3ea5d6194c5bfe42d77f"), ObjectId("5b3a374cd6194c5bfe3f5c9f"), ObjectId("5b3a33d9d6194c5bfe3db4e3"), ObjectId("5b3a3386d6194c5bfe3d8ab8"), ObjectId("5b3a3857d6194c5bfe3fd754") ], "count" : 9 }
{ "_id" : { "no" : 159374794 }, "uniqueIds" : [ ObjectId("5b3a3e52d6194c5bfe42b3b8"), ObjectId("5b3a3c0fd6194c5bfe41ac10"), ObjectId("5b3a38f5d6194c5bfe401b2f"), ObjectId("5b3a37afd6194c5bfe3f83b7"), ObjectId("5b3a33ebd6194c5bfe3dbc27"), ObjectId("5b3a36edd6194c5bfe3f2e78"), ObjectId("5b3a34ced6194c5bfe3e1b24"), ObjectId("5b3a3b36d6194c5bfe41530d"), ObjectId("5b3a3753d6194c5bfe3f5f99") ], "count" : 9 }
{ "_id" : { "no" : 159363089 }, "uniqueIds" : [ ObjectId("5b3a3e4fd6194c5bfe42b340"), ObjectId("5b3a3e0ad6194c5bfe429a1f"), ObjectId("5b3a3854d6194c5bfe3fd708"), ObjectId("5b3a34cbd6194c5bfe3e1acb"), ObjectId("5b3a38f4d6194c5bfe401afb"), ObjectId("5b3a36c4d6194c5bfe3f20aa"), ObjectId("5b3a3a06d6194c5bfe409119"), ObjectId("5b3a36ecd6194c5bfe3f2e2b"), ObjectId("5b3a3764d6194c5bfe3f6439") ], "count" : 9 }
{ "_id" : { "no" : 101412948 }, "uniqueIds" : [ ObjectId("5b3a3ea0d6194c5bfe42d708"), ObjectId("5b3a37b7d6194c5bfe3f8749"), ObjectId("5b3a3712d6194c5bfe3f4510"), ObjectId("5b3a334ed6194c5bfe3d759b"), ObjectId("5b3a3929d6194c5bfe403aca"), ObjectId("5b3a36f3d6194c5bfe3f334d"), ObjectId("5b3a39bad6194c5bfe407541"), ObjectId("5b3a3477d6194c5bfe3df66b"), ObjectId("5b3a35bdd6194c5bfe3e9233") ], "count" : 9 }
{ "_id" : { "no" : 107412155 }, "uniqueIds" : [ ObjectId("5b3a3e52d6194c5bfe42b3d1"), ObjectId("5b3a3a3bd6194c5bfe40a53a"), ObjectId("5b3a399cd6194c5bfe40678d"), ObjectId("5b3a390fd6194c5bfe402698"), ObjectId("5b3a3c0fd6194c5bfe41ac28"), ObjectId("5b3a346ad6194c5bfe3df338"), ObjectId("5b3a3584d6194c5bfe3e718a"), ObjectId("5b3a373cd6194c5bfe3f5563"), ObjectId("5b3a37e5d6194c5bfe3f97d6") ], "count" : 9 }
{ "_id" : { "no" : 156426829 }, "uniqueIds" : [ ObjectId("5b3a3cc6d6194c5bfe421829"), ObjectId("5b3a3f01d6194c5bfe430069"), ObjectId("5b3a3a29d6194c5bfe40a378"), ObjectId("5b3a37c9d6194c5bfe3f8fdc"), ObjectId("5b3a3558d6194c5bfe3e6b19"), ObjectId("5b3a3dabd6194c5bfe428666"), ObjectId("5b3a366ad6194c5bfe3f0356"), ObjectId("5b3a36e3d6194c5bfe3f2d02"), ObjectId("5b3a3798d6194c5bfe3f8160") ], "count" : 9 }
{ "_id" : { "no" : 104966976 }, "uniqueIds" : [ ObjectId("5b3a3c35d6194c5bfe41b614"), ObjectId("5b3a3a04d6194c5bfe4090e9"), ObjectId("5b3a3d19d6194c5bfe422451"), ObjectId("5b3a37a7d6194c5bfe3f82bc"), ObjectId("5b3a348cd6194c5bfe3e034c"), ObjectId("5b3a3e58d6194c5bfe42b5d2"), ObjectId("5b3a345cd6194c5bfe3deee2"), ObjectId("5b3a35aad6194c5bfe3e8b15"), ObjectId("5b3a36c3d6194c5bfe3f208b") ], "count" : 9 }
{ "_id" : { "no" : 105460396 }, "uniqueIds" : [ ObjectId("5b3a3e04d6194c5bfe429777"), ObjectId("5b3a3b99d6194c5bfe417eb6"), ObjectId("5b3a38c7d6194c5bfe400533"), ObjectId("5b3a3e6ed6194c5bfe42bbc6"), ObjectId("5b3a38f5d6194c5bfe401b1d"), ObjectId("5b3a3ee8d6194c5bfe42f43f"), ObjectId("5b3a39a5d6194c5bfe4069ec"), ObjectId("5b3a3a07d6194c5bfe409134") ], "count" : 8 }
{ "_id" : { "no" : 158805980 }, "uniqueIds" : [ ObjectId("5b3a3efad6194c5bfe42fc7c"), ObjectId("5b3a3abed6194c5bfe41470a"), ObjectId("5b3a337cd6194c5bfe3d89c3"), ObjectId("5b3a33bdd6194c5bfe3db218"), ObjectId("5b3a3dfcd6194c5bfe42955f"), ObjectId("5b3a3be7d6194c5bfe41a820"), ObjectId("5b3a3444d6194c5bfe3de564"), ObjectId("5b3a391fd6194c5bfe4039d5") ], "count" : 8 }
{ "_id" : { "no" : 107411546 }, "uniqueIds" : [ ObjectId("5b3a3c0fd6194c5bfe41ac2a"), ObjectId("5b3a3b37d6194c5bfe415337"), ObjectId("5b3a390fd6194c5bfe402699"), ObjectId("5b3a399cd6194c5bfe406793"), ObjectId("5b3a373cd6194c5bfe3f5565"), ObjectId("5b3a346ad6194c5bfe3df339"), ObjectId("5b3a3584d6194c5bfe3e718b"), ObjectId("5b3a37e5d6194c5bfe3f97d7") ], "count" : 8 }
{ "_id" : { "no" : 128015326 }, "uniqueIds" : [ ObjectId("5b3a3ed1d6194c5bfe42f1a3"), ObjectId("5b3a3df4d6194c5bfe4291f9"), ObjectId("5b3a38bed6194c5bfe400437"), ObjectId("5b3a381dd6194c5bfe3fd124"), ObjectId("5b3a3465d6194c5bfe3df1a7"), ObjectId("5b3a36cdd6194c5bfe3f2569"), ObjectId("5b3a3719d6194c5bfe3f4637"), ObjectId("5b3a377bd6194c5bfe3f7dfa") ], "count" : 8 }
{ "_id" : { "no" : 123932233 }, "uniqueIds" : [ ObjectId("5b3a3df3d6194c5bfe429177"), ObjectId("5b3a3d1dd6194c5bfe4224be"), ObjectId("5b3a3c39d6194c5bfe41b681"), ObjectId("5b3a3c0fd6194c5bfe41ac0d"), ObjectId("5b3a34e2d6194c5bfe3e22e6"), ObjectId("5b3a349fd6194c5bfe3e077d"), ObjectId("5b3a35aed6194c5bfe3e8b86"), ObjectId("5b3a3886d6194c5bfe3fea0f") ], "count" : 8 }
{ "_id" : { "no" : 150567857 }, "uniqueIds" : [ ObjectId("5b3a3a97d6194c5bfe413812"), ObjectId("5b3a39d9d6194c5bfe408888"), ObjectId("5b3a3816d6194c5bfe3fcd1b"), ObjectId("5b3a3635d6194c5bfe3ef80f"), ObjectId("5b3a3480d6194c5bfe3e011d"), ObjectId("5b3a34ead6194c5bfe3e2661"), ObjectId("5b3a33f8d6194c5bfe3dc477"), ObjectId("5b3a3529d6194c5bfe3e616a") ], "count" : 8 }
{ "_id" : { "no" : 143815726 }, "uniqueIds" : [ ObjectId("5b3a3b46d6194c5bfe415985"), ObjectId("5b3a3a08d6194c5bfe409172"), ObjectId("5b3a39a5d6194c5bfe4069fd"), ObjectId("5b3a33dad6194c5bfe3db527"), ObjectId("5b3a399cd6194c5bfe4067e7"), ObjectId("5b3a348fd6194c5bfe3e03a3"), ObjectId("5b3a37bcd6194c5bfe3f89c6"), ObjectId("5b3a36b7d6194c5bfe3f1cb9") ], "count" : 8 }
{ "_id" : { "no" : 143839331 }, "uniqueIds" : [ ObjectId("5b3a3ee8d6194c5bfe42f43a"), ObjectId("5b3a3e6ed6194c5bfe42bbbd"), ObjectId("5b3a3e04d6194c5bfe429773"), ObjectId("5b3a38c7d6194c5bfe40052f"), ObjectId("5b3a3a07d6194c5bfe40912e"), ObjectId("5b3a38f5d6194c5bfe401b19"), ObjectId("5b3a3b99d6194c5bfe417eb0"), ObjectId("5b3a39a5d6194c5bfe4069e8") ], "count" : 8 }
{ "_id" : { "no" : 99764925 }, "uniqueIds" : [ ObjectId("5b3a39f7d6194c5bfe408db1"), ObjectId("5b3a39c0d6194c5bfe4075eb"), ObjectId("5b3a399cd6194c5bfe40678a"), ObjectId("5b3a37bcd6194c5bfe3f89bf"), ObjectId("5b3a368ad6194c5bfe3f0673"), ObjectId("5b3a348fd6194c5bfe3e0391"), ObjectId("5b3a3578d6194c5bfe3e6e39"), ObjectId("5b3a36b7d6194c5bfe3f1ca8") ], "count" : 8 }
Question: What is the easiest and quickest way to remove the duplicates in Mongo 3.6.5? How must I edit the above command to achieve this?
I have tried the following but it doesn't work:
db.books.aggregate([ { $group:{ _id: {no: "$no" }, uniqueIds: { $addToSet: "$_id" }, count: {$sum: 1} } }, { $match: {count: {$gt: 1} } } ]).forEach(function(doc){ doc.uniqueIds.shift(); db.uniqueIds.remove({_id : {$in: doc.uniqueIds}});})
Mongo-3.6: Here ReviewId is my Unique Key, want to Delete my duplicate reviewId value
cursor=db.reviewsAnalysed.aggregate([{"$group": {"_id": {"reviewId":"$reviewId"},
"unique_ids": {"$addToSet": "$_id"}, "count": {"$sum": 1 } } }])
response = []
for doc in cursor:
del doc["unique_ids"][0]
for id in doc["unique_ids"]:
response.append(id)
db.reviewsAnalysed.remove({"_id": {"$in": response}})

Conditional Count in Subarray Using mongoDB

I have a large dataset that I'd like to use to describe performance of a test. The database is as follows:
db.test.insertMany({
"_id" : ObjectId("58e574a768afb6085ec3a388"),
"tests" : [
{
"name" : "2",
"evaluation" : [
{
"aHigh" : [1,2],
"aLow" : [ ],
"zHigh" : [ ],
"zLow" : [1,3]
},
{
"aHigh" : [1,4],
"aLow" : [2],
"zHigh" : [ 3],
"zLow" : [ ]
},
{
"aHigh" : [ ],
"aLow" : [1,2,3],
"zHigh" : [1,2,3,4],
"zLow" : [ ]
},]
}
]
},
{
"_id" : ObjectId("58eba09e51f7f631dd24aa1c"),
"tests" : [
{
"name" : "2",
"evaluation" : [
{
"aHigh" : [2],
"aLow" : [3 ],
"zHigh" : [ ],
"zLow" : [1,2,3,4]
},
{
"aHigh" : [ ],
"aLow" : [ ],
"zHigh" : [ ],
"zLow" : [3,4]
},
{
"aHigh" : [1,2],
"aLow" : [3,4],
"zHigh" : [ ],
"zLow" : [1,2,3,4]
},]
}
]
})
I have a set of conditional logic that I need to apply and count the number of outcomes. Essentially, I need to know how many evaluations meet a certain criteria. The logic is:
case1: if the `$size` of the array `aHigh` is `$gte` to 3 AND
if the `$size` of the array `aLow` is `$lt` to 1
then AHI
case2: if the `$size` of the array `aLow` is `$gte` to 3 AND
if the `$size` of the array `aHigh` is `$lt` to 1
then ALO
case3: if the `$sum` of `$size` of the array `aHigh` and the `$size` of the array `aLow` is `$gte` to 3
then AVR
My expected output is essentially a list. I want something to the effect of
{ "_id" : "AHI", "count" : 5 }
{ "_id" : "ALO", "count" : 15 }
{ "_id" : "AVR", "count" : 8 }
{ "_id" : "ZHI", "count" : 4 }
{ "_id" : "ZLO", "count" : 11 }
{ "_id" : "ZVR", "count" : 10 }
I cannot change the structure of the database. I have been using aggregate to get information. This code does not get me what I want, but it's what I've come up with so far.
db.test.aggregate([
{ $unwind: "$tests" },
    { $unwind: "$tests.evaluation" },
    { $unwind: "$tests.evaluation.aHigh"},
    { $unwind: "$tests.evaluation.aLow"},
{ $project: {
"results" :
{
$switch: {
branches: [
{
case: { $and : [ { $gte : [ { $size : "$tests.evaluation.aHigh" }, 1 ] },
{ $lt : [ { $size : "$tests.evaluation.aLow" }, 1 ] }
] },
then: "AHI"
},
{
case: { $and : [ { $gte : [ { $size : "$tests.evaluation.aLow" }, 1 ] },
{ $lt : [ { $size : "$tests.evaluation.aHigh" }, 1 ] }] },
then: "ALO"
},
{
case: { $gte : [ {$sum: [ {$size : "$tests.evaluation.aHigh" } , { $size : "$tests.evaluation.aLow" } ] }, 1 ] },
then: "AVR"
}
],
default: ""
}
}}}
])
edit:
I'd like to now be able to do the same thing for both the a and for the z.
You have one too many $unwind.
Updated your aggregation query to remove extra $unwindstage and added $group to count the results from $project stage.
db.test.aggregate([
{ $unwind: "$tests" },
{ $unwind: "$tests.evaluation" },
{ $project: {
"results" : {
$switch: {
branches: [
{
case: { $and : [ { $gte : [ { $size : "$tests.evaluation.aHigh" }, 1 ] },
{ $lt : [ { $size : "$tests.evaluation.aLow" }, 1 ] }
] },
then: "AHI"
},
{
case: { $and : [ { $gte : [ { $size : "$tests.evaluation.aLow" }, 1 ] },
{ $lt : [ { $size : "$tests.evaluation.aHigh" }, 1 ] }] },
then: "ALO"
},
{
case: { $gte : [ {$sum: [ {$size : "$tests.evaluation.aHigh" } , { $size : "$tests.evaluation.aLow" } ] }, 1 ] },
then: "AVR"
}
],
default: ""
}
}}},
{ $group:{_id:"$results", count:{$sum:1}}}
])

multiple group in mongodb

My collection look likes this.
{
"_id" : ObjectId("572c4ed33c1b5f51215219a8"),
"name" : "This is an angular course, and integeration with php",
"description" : "After we connected we can query or update the database just how we would using the mongo API with the exception that we use a callback. The format for callbacks is always callback(error, value) where error is null if no exception has occured. The update methods save, remove, update and findAndModify also pass the lastErrorObject as the last argument to the callback function.",
"difficulty_level" : "Beginner",
"type" : "Fast Track",
"tagged_skills" : [
{
"_id" : "5714e894e09a0f7d804b2254",
"name" : "PHP"
},
{
"_id" : "5717355806313b1f1715fa50",
"name" : "c++"
},
{
"_id" : "5715025bc2c5dbb4675180da",
"name" : "java"
},
{
"_id" : "5714f188ec325f5359979e33",
"name" : "symphony"
}
]}
I want to group by the collection on the basis of type,difficulty level and tagged skills and also get the count in a single query.
I am not been able to add skills count.
My query is as follows:-
db.course.aggregate([
{$unwind:"$tagged_skills"},
{$group:{
_id:null,
skills: { $addToSet: "$tagged_skills.name" },
Normal_df:{$sum:{
"$cond": [
{ "$eq":[ "$difficulty_level","Normal"] },
1,
0
]
}},
Beginner_df:{$sum:{
"$cond": [
{ "$eq":[ "$difficulty_level","Beginner"] },
1,
0
]
}},
Intermediate_df:{$sum:{
"$cond": [
{ "$eq":[ "$difficulty_level","Intermediate"] },
1,
0
]
}},
Advanced_df:{$sum:{
"$cond": [
{ "$eq":[ "$difficulty_level","Advanced"] },
1,
0
]
}},
Fast_Track_type:{$sum:{
"$cond": [
{ "$eq":[ "$type","Fast Track"] },
1,
0
]
}},
Normal_type:{$sum:{
"$cond": [
{ "$eq":[ "$type","Normal"] },
1,
0
]
}},
Beginner_type:{$sum:{
"$cond": [
{ "$eq":[ "$type","Beginner"] },
1,
0
]
}},
Normal_Track_type:{$sum:{
"$cond": [
{ "$eq":[ "$type","Normal Track"] },
1,
0
]
}},
}}
])
The result is as follows:-
{
"_id" : null,
"skills" : [
"SQL",
"PHP",
"java",
"Angular Js",
"Laravel 23",
"c++",
"Node Js",
"symphony",
"Mysql",
"Express Js",
"JAVA"
],
"Normal_df" : 1,
"Beginner_df" : 14,
"Intermediate_df" : 7,
"Advanced_df" : 2,
"Fast_Track_type" : 8,
"Normal_type" : 6,
"Beginner_type" : 1,
"Normal_Track_type" : 9
}
I also want to get all skills with their count.
To get all the skills with their count, you need to first get a list of all the skills. You can obtain this list with running a distinct command on the approapriate fields. With this list you can then construct the appropriate $group pipeline document that will use the $sum and $cond operators.
Consider the following use case:
var difficultyLevels = db.course.distinct("difficulty_level"),
types = db.course.distinct("type"),
skills = db.course.distinct("tagged_skills.name"),
unwindOperator = { "$unwind": "$tagged_skills" },
groupOperator = {
"$group": {
"_id": null,
"skills": { "$addToSet": "$tagged_skills.name" }
}
};
difficultyLevels.forEach(function (df){
groupOperator["$group"][df+"_df"] = {
"$sum": {
"$cond": [ { "$eq": ["$difficulty_level", df] }, 1, 0]
}
}
});
types.forEach(function (type){
groupOperator["$group"][type.replace(" ", "_")+"_type"] = {
"$sum": {
"$cond": [ { "$eq": ["$type", type] }, 1, 0]
}
}
});
skills.forEach(function (skill){
groupOperator["$group"][skill] = {
"$sum": {
"$cond": [ { "$eq": ["$tagged_skills.name", skill] }, 1, 0]
}
}
});
//printjson(groupOperator);
db.course.aggregate([unwindOperator, groupOperator]);
In the first line, we obtain an array with the difficulty levels by running the distinct command on the difficulty_level field
db.course.distinct("difficulty_level")
This will produce the array
var difficultyLevels = ["Normal", "Beginner", "Intermediate", "Advanced"]
Likewise, the preceding distinct operations will return the list of possible unique values for that key.
After getting these lists, you can then create the pipeline objects using the forEach() method to populate the document keys for each given item in the list. You can then use the resulting document, which will look like this
printjson(groupOperator);
{
"$group" : {
"_id" : null,
"skills" : {
"$addToSet" : "$tagged_skills.name"
},
"Beginner_df" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$difficulty_level",
"Beginner"
]
},
1,
0
]
}
},
"Intermediate_df" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$difficulty_level",
"Intermediate"
]
},
1,
0
]
}
},
"Fast_Track_type" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$type",
"Fast Track"
]
},
1,
0
]
}
},
"PHP" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$tagged_skills.name",
"PHP"
]
},
1,
0
]
}
},
"c++" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$tagged_skills.name",
"c++"
]
},
1,
0
]
}
},
"java" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$tagged_skills.name",
"java"
]
},
1,
0
]
}
},
"symphony" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$tagged_skills.name",
"symphony"
]
},
1,
0
]
}
},
"C#" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$tagged_skills.name",
"C#"
]
},
1,
0
]
}
},
"Scala" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$tagged_skills.name",
"Scala"
]
},
1,
0
]
}
},
"javascript" : {
"$sum" : {
"$cond" : [
{
"$eq" : [
"$tagged_skills.name",
"javascript"
]
},
1,
0
]
}
}
}
}