【发布时间】:2015-05-03 13:24:09
【问题描述】:
我有一个带有标签子文档的文档集合。
{
title:"my title",
slug:"my-title",
tags:[
{tagname:'tag1', id:1},
{tagname:'tag2', id:2},
{tagname:'tag3', id:3}]
}
{
title:"my title2",
slug:"my-title2",
tags:[
{tagname:'tag1', id:1},
{tagname:'tag2', id:2}]
}
{
title:"my title3",
slug:"my-title3",
tags:[
{tagname:'tag1', id:1},
{tagname:'tag3', id:3}]
}
{
title:"my title4",
slug:"my-title4",
tags:[
{tagname:'tag1', id:1},
{tagname:'tag2', id:2},
{tagname:'tag3', id:3}]
}
[...]
使用 $unwind + group count 聚合来获取每个标签的计数非常简单
但是,我想找出一起找到的标签的计数,或者更准确地说,哪个兄弟姐妹最常出现在彼此旁边,按计数排序。我没有找到示例,也无法弄清楚如何在没有多个查询的情况下执行此操作。
理想的最终结果是:
{'tag1':{
'tag2':3, // tag1 and tag2 were found in a document together 3 times
'tag3':3, // tag1 and tag3 were found in a document together 3 times
[...]}}
{'tag2':{
'tag1':3, // tag2 and tag1 were found in a document together 3 times
'tag3':2, // tag2 and tag3 were found in a document together 2 times
[...]}}
{'tag3':{
'tag1':3, // tag3 and tag1 were found in a document together 3 times
'tag2':2, // tag3 and tag2 were found in a document together 2 times
[...]}}
[...]
【问题讨论】:
-
我认为您的意思是
"tags": [ {} ],因为与您键入的内容相比,这将是数组语法,这实际上不是有效的文档结构。您不能使用聚合框架创建任意“键名”。它似乎也不太可能获得您想要的结果(或接近它),但我真的只是在猜测,因为您的问题缺乏可能产生明确预期结果的明确样本。见:How to Create a Minimal, Complete and Verifiable Example -
这只是简单的简化,原始文件很大,子文件也很大。
-
见您更正了数组表示法。不要求您提交整个事情,只是一个样本和一个可以从该样本中的数据实际获得(期望)的结果。它使您的问题比现在更清楚。
-
是否足够清楚,还是您需要进一步澄清。
-
“根据您提供的单个文档数据样本,我们如何获得您所期望的结果?”我们不可以。因此,我要求您提供足够的文档,以便能够产生您期望的示例输出。
标签: javascript mongodb mongodb-query aggregation-framework