0

I have a Sequence : [k1,k4,k6,k10]and a MongoDB object as follows:{"_id" : "x" , "k" : [ "k1", "k2 ","k6"]},{"_id" : "y" , "k" : [ "k2", "k4 ","k10","k11"]},{"_id" : "z" , "k" : [ "k4", "k6 ","k10","k12"]}

I have to find the particular object which has a maximum number of matching elements from the array.In this case, it will be "z" as it has three matching elements in the "k" array i,e ["k4","k6","k10"].

So I wanted to know that is there a MongoDB way of doing?

Himanshu Sharma
  • 2,940
  • 1
  • 7
  • 18
zolo
  • 7
  • 4

1 Answers1

1

You can use this query :

db.data.aggregate([{
    $match: {
        k: {
            $in: ["k1", "k4", "k6", "k10"]
        }
    }
}, {
    $addFields: {
        count: {
            $size:{
                $setIntersection: [
                    ["k1", "k4", "k6", "k10"], "$k"
                ]
            }
        }
    }
}, {
    $sort: {
        count: -1
    }
}, {
    $limit: 1
}])

This query will :

  • filter on relevant records (non-necessary but better perfs with it)
  • Calculate the count of matching elements using the set intersection
  • sort them by count descending
  • return the first record

Note: There can be multiple records with maximum matches, the above query gets you only one.

Himanshu Sharma
  • 2,940
  • 1
  • 7
  • 18
Julien TASSIN
  • 5,004
  • 1
  • 25
  • 40