计算数组中多个项的出现次数

时间:2014-08-22 16:46:58

标签: json mongodb database

我有这样的文件

{
"text": "test description",
"tags": ["house", "garden", "wall"]
}

现在,如果我想在MongoDB中匹配乘法标签,那么

db.test.find( { tags: { $in: [ "house", "garden", "fish" ] } } );

是否有方法可以获取每个文档的匹配标记量(例如使用$ meta:“textScore”进行文本搜索) 这样我可以按降序排序文档与查询的匹配程度?

对于我上面的例子,我想知道有2个匹配的标签。

1 个答案:

答案 0 :(得分:1)

我认为你必须使用aggregation framework

像这样的东西

db.test.aggregate( {$unwind:'$tags'},
                   {$match: {tags:{$in: ["house", "garden", "fish"]}}},
                   {$group: {_id:'$_id', tagcount:{$sum: 1}}} )

说明:

  • $unwind部分为标签数组中的每个元素生成一个文档
  • $match从那些与列表中的标签匹配的文档中选择
  • $group对按_id分组的文档进行润色并计算每个匹配的文档

结果应该是

形式的文档列表
{_id: id, tagcount: #matching tags}

您还可以在最后添加sort,例如

{$sort:{tagcount : -1}}

因此,对您的结构进行聚合查询,以返回_id,文本,匹配标记和匹配标记的数量,这些标记按匹配标记的数量降序排序:

db.test.aggregate( {$unwind:'$tags'},
                   {$match: {tags:{$in: ["house", "garden", "fish"]}}},
                   {$group: {_id: '$_id' , text : {$first:'$text'},
                             tags:{$addToSet:'$tags'}, tagcount:{$sum: 1}}},
                   {$sort:{tagcount:-1}})

您的示例文档的结果

{ "_id" : ObjectId("5..."), 
  "text" : "test description", 
  "tags" : [ "garden", "house" ],
  "tagcount" : 2 }
相关问题