1

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
  • 1
    better this way @Alrick ? Commented Mar 19, 2019 at 15:04

1 Answer 1

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"
    ]
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.