【问题标题】:How to use Mongo aggregate to create distinct items from array如何使用 Mongo 聚合从数组中创建不同的项目
【发布时间】:2021-05-22 00:21:25
【问题描述】:

我无法理解如何在 Mongo 中使用聚合管道。

给定以下文件列表:

db.dishes.insertMany([
    {_id: "Vanilla Sundae", keywords: ["vanilla", "ice cream", "desert"] },
    {_id: "Vanilla Cake", keywords: ["vanilla", "cake", "baking", "desert"] },
    {_id: "Chocolate Cake", keywords: ["chocolate", "cake", "baking", "desert"] }
])

如何创建一个聚合,该聚合将返回 keywords 的不同关键字列表和文档计数:

[
    {"_id": "vanilla", "count": 2},
    {"_id": "ice cream", "count": 1},
    {"_id": "desert", "count": 3},
    {"_id": "baking", "count": 2},
    {"_id": "cake", "count": 2},
    {"_id": "chocolate", "count": 1}
]

【问题讨论】:

  • 这个答案对你有帮助吗?

标签: mongodb aggregate


【解决方案1】:

你可以使用$unwind$group来解构和重构数组

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

工作Mongo playground

【讨论】:

    【解决方案2】:

    您可以使用 unwind 结合 group 运算符来实现这一点。

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

    这应该可以解决问题! :)

    我正在附加 MongoDB 游乐场here

    【讨论】:

      猜你喜欢
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 2015-01-02
      • 1970-01-01
      相关资源
      最近更新 更多