How to find common element in these array! Here ("a":2) is present in all

/* 1 */
{
“completed_users” : [
{
“a” : 2.0
},
{
“b” : 2.0
},
{
“c” : 3.0
},
{
“d” : 4.0
},
{
“e” : 5.0
}
]
}

/* 2 */
{
“completed_users” : [
{
“a”:2
}
]
}

/* 3 */
{
“completed_users” : [
{
“a” : 2.0
},
{
“b” : 2.0
},
{
“c” : 3.0
},
{
“d” : 4.0
},
{
“e” : 5.0
}
]
}

Hi @paresh_saraf1,

Interesting question!!

Please allow me some time to look into it and get back to you.

Thanks,
Sonali

@paresh_saraf1 is this an assignment from somewhere else?

If it is and you think about the Maths, you’ll be able to come up with the aggregation for this:

Assuming all completed_users are arrays of key-value pairs and are present in every document:

  • Deconstruct the array
  • Get a count of each key-value pair
  • Sort in descending

I don’t want the count of each key-value pairs.I just want the intersection of these arrays !

Thank you for the attempt! Appreatiate it

Thank you for the reply !
Please let me know the answer once you go through it.

Hi @paresh_saraf1,

The one thing that we can do here is :
First combine the completed_users array into a single array using $push operation in the $group stage.
Then in the $project stage you can apply $setIntersection to the in field of the $reduce operator where $this and $value can help iterating through the combined array by referencing the element being processed and cumulative value of the expression respectively.

I hope it helps!!
Please let me know, if you have any questions.

Thanks,
Sonali

1 Like