简体   繁体   中英

mongodb use $count in aggregation

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

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"
    ]
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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