繁体   English   中英

MongoDB 聚合:计算数组中的不同字段

[英]MongoDB Aggregation: Counting distinct fields from array

需要使用JSmongodb查询中计算所有寄存器上的不同标签。

寄存器结构:

  {
  "_id": {
    "$oid": "62e593aed8fd9808777225e8"
  },
  "title": "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”",
  "author": {
    "name": "Albert Einstein",
    "url": "https://quotes.toscrape.com/author/Albert-Einstein"
  },
  "tag": [
    "change",
    "deep-thoughts",
    "thinking",
    "world"
  ]
  }

这可能很有用。 除了获取字段的不同值外,它还返回出现次数:

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

你可以在这里试试: https://mongoplayground.net/p/yXLYkJKO3Wf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM