【问题标题】:MongoDB Matching after aggregation聚合后的MongoDB匹配
【发布时间】: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


    【解决方案1】:

    最后一个聚合管道应该是

    {$match : {"_id.tagurl" : {$regex : "veg"}}}
    

    {$match : {"_id.tagurl" : /veg/}}
    

    使用点符号导航到嵌入或子元素

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 2019-01-24
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 2022-06-16
      相关资源
      最近更新 更多