I'm looking to make a perfect match between users using mongoose.
Here is an example of a schema:
username: "Nicolas",
fruitiwant:["apple", "orange"]
fruitihave: ["banana"]
I want to have a json that displays users who have a perfect match. User A wants the fruit that user B has. User B wants the fruit that user A has.
Thanks for your answers.
CodePudding user response:
What we can do is use $lookup
to match all users from the collection that suffice the condition, we then just have to group to eliminate duplicate couples, like so:
db.collection.aggregate([
{
$lookup: {
from: "collection",
let: {
ihave: "$bookihave",
iwant: "$fruitiwant",
id: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$ne: [
"$_id",
"$$id"
]
},
{
$gt: [
{
$size: {
"$setIntersection": [
"$$ihave",
"$fruitiwant"
]
}
},
0
]
},
{
$gt: [
{
$size: {
"$setIntersection": [
"$$iwant",
"$bookihave"
]
}
},
0
]
}
]
}
}
},
{
$project: {
username: 1,
}
}
],
as: "perfect"
}
},
{
$unwind: "$perfect"
},
{
$project: {
matchedUserNames: {
$cond: [
{
$gt: [
"$username",
"$perfect.username"
]
},
[
"$perfect.username",
"$username",
],
[
"$username",
"$perfect.username"
]
]
}
}
},
{
$group: {
_id: "$matchedUserNames"
}
}
])