【问题标题】:Mongodb counting combination of items in arrayMongodb计数数组中的项目组合
【发布时间】:2021-11-18 08:37:37
【问题描述】:

我有类似的东西: `

[
{
    ....
    tags : ["A","B"]
},
{
    ....
    tags : ["A","B"]
},
{
    ....
    tags : ["J","K"]
},
{
    ....
    tags : ["A","B","C"]
}
]`

使用聚合框架,我想按数组组合进行分组,以得到类似这样的东西:

[
{
    _id:["A","B"],
    count : 3
},
{
    _id:["J","K"],
    count : 1
},
{
    _id:["A","C"],
    count : 1

   },
{
        _id:["B","C"],
        count : 1
    },
]

有可能吗?提前致谢

【问题讨论】:

    标签: mongodb aggregation-framework aggregation


    【解决方案1】:

    查询

    • 对于每个大小为 1 的标签,使其成为 ["V"] -> ["V" null] (如果您不想计算带有 null 的对,可以在最终结果中过滤掉)
    • 地图,对于每个成员,我们与其他成员一起说 例如["A" "B" "C"] 将与["B" "C"] 一起构成“A”, "B" 加上["A" "C"] 等(我们计算双倍,接下来除以 2)
    • 展开该数组
    • 成对分组,但短路对["A" "B"] = ["B" "A"]
    • 计数为 0.5(而不是 1)(就像我们除以 2)

    Test code here

    aggregate(
    [ {
      "$set" : {
        "tags" : {
          "$cond" : [ {
            "$eq" : [ {
              "$size" : "$tags"
            }, 1 ]
          }, {
            "$concatArrays" : [ "$tags", [ null ] ]
          }, "$tags" ]
        }
      }
    }, {
      "$set" : {
        "a" : {
          "$map" : {
            "input" : "$tags",
            "in" : {
              "member" : "$$t",
              "togetherWith" : {
                "$setDifference" : [ "$tags", [ "$$t" ] ]
              }
            },
            "as" : "t"
          }
        }
      }
    }, {
      "$unwind" : {
        "path" : "$a"
      }
    }, {
      "$replaceRoot" : {
        "newRoot" : "$a"
      }
    }, {
      "$unwind" : {
        "path" : "$togetherWith"
      }
    }, {
      "$group" : {
        "_id" : {
          "$cond" : [ {
            "$lt" : [ "$member", "$togetherWith" ]
          }, [ "$member", "$togetherWith" ], [ "$togetherWith", "$member" ] ]
        },
        "count" : {
          "$sum" : 0.5
        }
      }
    }, {
      "$set" : {
        "count" : {
          "$toInt" : "$count"
        }
      }
    } ]
    )
    

    【讨论】:

      【解决方案2】:

      您可以使用unwind 将数组元素拆分为单独的文档。

      然后你可以将每个相加得到结果。

      db.collection.aggregate([
      {  $unwind : "$newTags"  },
      {  $group:
        { "_id" : "$newTags",
         "count":{$sum:1}
        }
      }])
      
      

      【讨论】:

        猜你喜欢
        • 2014-02-18
        • 1970-01-01
        • 2015-01-10
        • 1970-01-01
        • 2017-11-19
        • 2018-12-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多