我有一个“项目”的集合,其中包含一个搜索标签列表。当用户在标签字段中输入内容时,我想用该标签属于多少项的计数来过滤所有匹配的标签。我最初使用的是此查询:
db.kCItem.aggregate(
[{$match:{searchTags:{$elemMatch:{tagLabel:{$regex:".*veg.*"}}}}},
{$unwind:"$searchTags"},
{$group:{_id:{tagurl:{$toLower:'$searchTags._id'},
label:"$searchTags.tagLabel"}, count: {$sum:1}}}])
这将返回如下列表:
{ "_id" : { "tagurl" : "vegetarian", "label" : "vegetarian" }, "count" : 1 }
{ "_id" : { "tagurl" : "veg", "label" : "veggie" }, "count" : 1 }
不幸的是,此查询还带回了与不匹配正则表达式的项目相关联的“其他”标签(不匹配正则表达式)。我的计划是在聚合中添加一个额外的$ match:
db.kCItem.aggregate([
{$match:{searchTags:{$elemMatch:{tagLabel:{$regex:".*waffle.*"}}}}},
{$unwind:"$searchTags"},
{$group:{_id:{tagurl:{$toLower: '$searchTags._id'},label:"$searchTags.tagLabel"}, count: {$sum:1}}},
{$match:{_id:{label:{$regex:"*"}}}} ])
但是,即使使用*作为正则表达式,我也没有得到任何退回的物品。
答案 0 :(得分:0)
最后一个聚合管道应该是
{$match : {"_id.tagurl" : {$regex : "veg"}}}
或
{$match : {"_id.tagurl" : /veg/}}
使用点表示法导航到嵌入式或子元素