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!
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.