mongodb use $count in aggregation

时间:2019-03-19 14:49:32

标签: arrays mongodb aggregation-framework

I have a collection of cars where one of the fields is an array, let's say something like :

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

and I have an array of designers, let's say something like :

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

and I want to count how many first are within designers.

For example:

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

desire result: count = 1

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

desire result: count = 1

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

desire result: count = 2

1 个答案:

答案 0 :(得分:1)

setIntersection is the way to achieve this.

Taking this document :

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

You can apply the following aggregate query to retrieve elements that are both in designers and topDesigners arrays. And $size to get the size of this new array :

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

Will result in :

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