mongodb - Aggregate on tags regex -
mongodb - Aggregate on tags regex -
i looking way count number of tags exist documents.
data looks following:
[ { "_id": objectid("...."), "tags": ["active-adult", "active-tradeout"] }, { "_id": objectid("...."), "tags": ["active-child", "active-tradeout", "active-junk-tag"] }, { "_id": objectid("...."), "tags": ["inactive-adult"] } ]
this how result of aggregation like:
[ { "_id": "active", "total": 2, "subtags": { "adult": 1, "child": 1, "tradeout": 2, "junk-tag": 1 } }, { "_id": "inactive", "total": 1, "subtags": { "adult": 1 } } ]
i know can count tags, looking regex
db.user.aggregate([ {$unwind: "$tags"}, {$group: {_id: "$tags", total: {$sum: 1}}} ])
you can little string processing $substr
, $cond
operators desired result (there no need regex). require mongodb 2.6+:
db.user.aggregate([ { $unwind : "$tags"}, { $project : { tagtype : { $cond : { if : { $eq : [ { $substr : [ "$tags", 0, 6] }, "active" ]}, then: "active", else: "inactive"} }, tag: { $cond : { if : { $eq : [ { $substr : [ "$tags", 0, 6] }, "active" ]}, then: { $substr : ["$tags", 7, -1]}, else: { $substr : ["$tags", 9, -1]}} } }}, { $group : { _id : {tagtype : "$tagtype", tag: "$tag"} , total: { $sum: 1}}}, { $group : { _id : "$_id.tagtype", subtags: { $push : {tag : "$_id.tag", total: "$total"}}, total: { $sum : "$total"}}} ]);
the result of query this:
{ "_id" : "inactive", "subtags" : [ { "tag" : "adult", "total" : 1 } ], "total" : 1 } { "_id" : "active", "subtags" : [ { "tag" : "junk-tag", "total" : 1 }, { "tag" : "child", "total" : 1 }, { "tag" : "tradeout", "total" : 2 }, { "tag" : "adult", "total" : 1 } ], "total" : 5 }
edit:
i noticed total in result counting total number of tags not number of documents had @ to the lowest degree 1 active tag. query give exact output wanted, although more complicated:
db.user.aggregate([ /* unwind can process each tag array */ { $unwind : "$tags"}, /* remove active/inactive strings tag values , create new value tagtype */ { $project : { tagtype : { $cond : { if : { $eq : [ { $substr : [ "$tags", 0, 6] }, "active" ]}, then: "active", else: "inactive"} }, tag: { $cond : { if : { $eq : [ { $substr : [ "$tags", 0, 6] }, "active" ]}, then: { $substr : ["$tags", 7, -1]}, else: { $substr : ["$tags", 9, -1]}} } }}, /* grouping documents tag type, can find num. of docs tag type (total) */ { $group : { _id : "$tagtype", tags :{ $push : "$tag"}, docid :{ $addtoset : "$_id"}}}, /* project values can 'total' tag type */ { $project : { tagtype : "$_id", tags : 1, "doctotal": { $size : "$docid" }}}, /* must unwind total count each tag */ { $unwind : "$tags"}, /* sum tags type , tag value */ { $group : { _id : {tagtype : "$tagtype", tag: "$tags"} , total: { $sum: 1}, doctotal: {$first : "$doctotal"}}}, /* grouping tagtype can subtags */ { $group : { _id : "$_id.tagtype", subtags: { $push : {tag : "$_id.tag", total: "$total"}}, total: { $first : "$doctotal"}}} ]);
regex mongodb aggregate
Comments
Post a Comment