Hi, I’m looking for the most performant way to count unique subdocuments for each document returned.
My abbreviated data models is in the shape:
const myCollection = [
{
_id: "123",
animals: [{ name: "cat" }, { name: "cat" }, { name: "cat" }],
fruits: [{ name: "apple" }, { name: "orange" }, { name: "orange" }],
},
{
_id: "456",
animals: [{ name: "cat" }, { name: "dog" }, { name: "bird" }],
fruits: [{ name: "apple" }, { name: "pear" }, { name: "mango" }],
},
];
My desired outcome is:
const desiredResult = [
{
_id: "123",
animals: [{ name: "cat" }, { name: "cat" }, { name: "cat" }],
fruits: [{ name: "apple" }, { name: "orange" }, { name: "orange" }],
unique_animals_count: 1,
unique_fruits_count: 2,
},
{
_id: "456",
animals: [{ name: "cat" }, { name: "dog" }, { name: "bird" }],
fruits: [{ name: "apple" }, { name: "pear" }, { name: "mango" }],
unique_animals_count: 3,
unique_fruits_count: 3,
},
];
I have tried a vast array of $unwind, $group and the like, but hours later and a ton of Googling I’ve still not found the answer. And, part of me feels it’s not overly tricky to do … I’m just not landing on it!
Any help would be greatly appreciated.