首页 > 解决方案 > mongodb 在聚合中使用 $count

问题描述

我有一组汽车,其中一个字段是一个数组,让我们说一下:

"designers": [
    "John Smith",
    "Jane Smith",
]

我有很多设计师,让我们说一下:

"topDesigners": [
    "Brad Johnson",
    "Kevin Williams",
    "John Smith"
]

我想数一数设计师中有多少是第一位的。

例如:

"designers": [
    "Kevin Williams",
    "Jane Smith",
]

期望结果:count = 1

 "designers": [
    "Jane Smith",
    "John Smith"
]

期望结果:count = 1

 "designers": [
    "Kevin Huntzberger",
    "Brad Johnson",
    "John Smith"
]   

期望结果:count = 2

标签: arraysmongodbaggregation-framework

解决方案


setIntersection是实现这一点的方法。

拿着这份文件:

    {
    designers: [
      "John Smith",
      "Jane Smith"
    ],
    topDesigners: [
      "Brad Johnson",
      "Kevin Williams",
      "John Smith"
      ]
  }

您可以应用以下聚合查询来检索设计器和 topDesigners 数组中的元素。和 $size 来获取这个新数组的大小:

db.collection.aggregate([
  {
    $project: {
      designers: "$designers",
      topDesigners: "$topDesigners",
      areInBoth: {
        $setIntersection: [
          "$designers",
          "$topDesigners"
        ]
      },
      areInBothSize: {
        $size: {
          $setIntersection: [
            "$designers",
            "$topDesigners"
          ]
        }
      }
    }
  }
])

将导致:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "areInBoth": [
      "John Smith"
    ],
    "areInBothSize": 1,
    "designers": [
      "John Smith",
      "Jane Smith"
    ],
    "topDesigners": [
      "Brad Johnson",
      "Kevin Williams",
      "John Smith"
    ]
  }
]

推荐阅读