我有一个包含子文档标签的文件集合。
{
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": [{}]
,因为这是数组语法,与你输入的内容相比,它才是正确的文档结构。你不能使用聚合框架创建任意的“键名”。而且看起来也不太可能得到你想要的结果(或接近),但我只是猜测,因为你的问题缺乏一个可以产生清晰预期结果的明确示例。请参见:如何创建一个最小化、完整和可验证的示例。 - Neil Lunn