我正在寻找一种方法来计算文档中存在的标签数量。
数据如下所示:
[
{
"_id": ObjectId("...."),
"tags": ["active-adult", "active-tradeout"]
},
{
"_id": ObjectId("...."),
"tags": ["active-child", "active-tradeout", "active-junk-tag"]
},
{
"_id": ObjectId("...."),
"tags": ["inactive-adult"]
}
]
这就是我希望聚合结果如下所示:
[
{
"_id": "active",
"total": 2,
"subtags": {
"adult": 1,
"child": 1,
"tradeout": 2,
"junk-tag": 1
}
},
{
"_id": "inactive",
"total": 1,
"subtags": {
"adult": 1
}
}
]
我知道我可以计算标签,但我正在寻找正则表达式
db.User.aggregate([
{$unwind: "$tags"},
{$group: {_id: "$tags", total: {$sum: 1}}}
])
答案 0 :(得分:1)
您可以使用$substr
和$cond
运算符进行一些字符串处理,以获得所需的结果(不需要正则表达式)。这将需要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"}}}
]);
此查询的结果将是:
{
"_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
}
修改强>
我刚注意到结果中的总数是计算标签总数而不是至少有一个活动标签的文档数。此查询将为您提供所需的确切输出,但稍微复杂一些:
db.User.aggregate([
/* unwind so we can process each tag from the array */
{ $unwind : "$tags"},
/* Remove the active/inactive strings from the tag values
and create a 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]}}
}
}},
/* Group the documents by tag type, so we can
find num. of docs by tag type (total) */
{ $group : { _id : "$tagType",
tags :{ $push : "$tag"},
docId :{ $addToSet : "$_id"}}},
/* project the values so we can get the 'total' for tag type */
{ $project : { tagType : "$_id",
tags : 1,
"docTotal": { $size : "$docId" }}},
/* we must unwind to get total count for each tag */
{ $unwind : "$tags"},
/* sum the tags by type and tag value */
{ $group : { _id : {tagType : "$tagType", tag: "$tags"} ,
total: { $sum: 1}, docTotal: {$first : "$docTotal"}}},
/* finally group by tagType so we can get subtags */
{ $group : { _id : "$_id.tagType",
subtags: { $push : {tag : "$_id.tag", total: "$total"}},
total: { $first : "$docTotal"}}}
]);