【发布时间】:2018-12-20 04:52:27
【问题描述】:
我有一个“项目”集合,其中包含一个搜索标签列表。作为用户在标签字段中键入的内容,我想过滤所有匹配的标签,并计算该标签所属的项目数。我最初使用的是这个查询:
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:"*"}}}} ])
但是,即使使用 * 作为正则表达式,当我这样做时,我也没有返回任何物品。
【问题讨论】:
标签: mongodb mongodb-query