Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
Query for similar array in MongoDB

I'd like to search for documents with similar arrays in my MongoDB collection and order by similarity value.

Example:

I would search for {chars:['a', 'b', 'c']}

And I have stored those documents:

1. {chars:['s', 'e', 'c']}
2. {chars:['i', 'l', 'd']}
3. {chars:['b', 'a', 'c']}
4. {chars:['f', 'c', 'b']}

I'd like to get something ORDERED like:

[
  {chars:['b', 'a', 'c'], similarity: 1.0},
  {chars:['f', 'c', 'b'], similarity: 0.66},
    ...
]

Which operator or query strategy should I use to get something like that?

Thanks!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Thanks to all that tried to help me. I appreciate your help.

I have found a solution via aggregation pipeline.

var myArray = ['a', 'b', 'c'];

db.test.aggregate([
    {
        $unwind: '$chars',
    },
    {
        $match: { chars: { $in: myArray } },
    },
    {
        $group: {
            _id: '$_id',
            count: { $sum: 1 },
        },
    },
    {
        $project: {
            _id: 1,
            count: 1,
            score: { $divide: ['$count', myArray.length] },
        },
    },
    {
        $sort: { score: -1 },
    },
]);

This is what console gives back:

{ "_id" : ObjectId("586ebeacb2ec9fc7fef5ce31"), "count" : 3, "score" : 1 }
{ "_id" : ObjectId("586ebeb9b2ec9fc7fef5ce32"), "count" : 2, "score" : 0.6666666666666666 }
{ "_id" : ObjectId("586ebe89b2ec9fc7fef5ce2f"), "count" : 1, "score" : 0.3333333333333333 }

Hope somebody finds this usefull.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!