如何对 mongoDB collection 中的字段进行分组和计数

How to group and a count fields in a mongoDB collection

我真的是 mongodb 的新手,来自 sql 背景,正在努力研究如何 运行 一个简单的报告,该报告将嵌套文档中的值与一个计数,并以计数最高的顺序排序。

我已经尝试了很多在网上找到的方法,但我无法定位到分组所需的确切字段。

这里是 collection.

{
    "_id": {
        "$oid": "6005f95dbad14c0308f9af7e"
    },
    "title": "test",
    "fields": {
        "6001bd300b363863606a815e": {
            "field": {
                "_id": {
                    "$oid": "6001bd300b363863606a815e"
                },
                "title": "Title Two",
                "datatype": "string"
            },
            "section": "Section 1",
        },
        "6001bd300b363863423a815e": {
            "field": {
                "_id": {
                    "$oid": "6001bd3032453453606a815e"
                },
                "title": "Title One",
                "datatype": "string"
            },
            "section": "Section 1",
        },
        "6001bd30453534863423a815e": {
            "field": {
                "_id": {
                    "$oid": "6001bd300dfgdfgdf06a815e"
                },
                "title": "Title One",
                "datatype": "string"
            },
            "section": "Section 1",
        }
    },
    "sections": ["Section 1"]
}

我需要从上面的例子中得到的结果是:

“标题一”,2

"标题二", 1

谁能给我指出正确的方向?非常感谢。

具有动态字段名称通常是一个糟糕的设计。

试试这个:

db.collection.aggregate([
   { $set: { fields: { $objectToArray: "$fields" } } },
   { $unwind: "$fields" },
   { $group: { _id: "$fields.v.field.title", count: { $count: {} } } },
   { $sort: { count: -1 } }
])

这是另一种方法。 $project 丢弃了除 deep-dive 到 "title" 之外的所有内容。然后 $unwind$sortByCount.

db.collection.aggregate([
  {
    "$project": {
      "titles": {
        "$map": {
          "input": {
            "$objectToArray": "$fields"
          },
          "in": "$$this.v.field.title"
        }
      }
    }
  },
  {
    "$unwind": "$titles"
  },
  {
    "$sortByCount": "$titles"
  }
])

mongoplayground.net 上试一试。