【问题标题】:I have documents with similar values of fields I want to get max times repeated values from documents我有具有相似字段值的文档我想从文档中获取最大次数重复值
【发布时间】:2022-01-16 02:01:13
【问题描述】:

考虑以下数据:

{ 
  "_id" : ObjectId("61e14ce9d1cb1903c6158068"),
  "quesOne" : 1, 
  "quesTwo" : 2,
  "quesThree" : 3, 
  "quesFour" : 2, 
  "quesFive" : 2, 
  "quesSix" : 3, 
  "quesSeven" : 1, 
  "quesEight" : 4, 
  "quesNine" : 3, 
  "quesTen" : 4
}

我想要输出如下:总共 10 个问题

Value times
4 2
3 3
2 3
1 2

值 2 和 3 的最大计数

第二个文档:

{ 
  "_id" : ObjectId("61dfd0e0d1cb196f0b9473da"), 
  "quesOne" : 2, 
  "quesTwo" : 2,
  "quesThree" : 4, 
  "quesFour" : 2, 
  "quesFive" : 4, 
  "quesSix" : 3, 
  "quesSeven" : 4, 
  "quesEight" : 4, 
  "quesNine" : 3, 
  "quesTen" : 4
}

输出:总共 28 个问题

Value times
4 5
3 2
2 3
1 0

值 4 的最大计数

这可以通过 MongoDB 查询聚合实现吗?

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework aggregate-functions


    【解决方案1】:

    您可以使用$objectToArray$$ROOT 对象转换为k-v 元组数组,以便首先处理。然后$unwind数组和$group通过v进行分组计数。

    db.collection.aggregate([
      {
        $match: {
          "_id": ObjectId("61e14ce9d1cb1903c6158068")
        }
      },
      {
        $project: {
          _id: 0
        }
      },
      {
        $project: {
          arr: {
            "$objectToArray": "$$ROOT"
          }
        }
      },
      {
        "$unwind": "$arr"
      },
      {
        $group: {
          _id: "$arr.v",
          count: {
            $sum: 1
          }
        }
      }
    ])
    

    这是Mongo playground 供您参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多