Created
June 18, 2018 20:22
-
-
Save barisusakli/3b80c4ee4afb1e4fa11df2fcc979d5ef to your computer and use it in GitHub Desktop.
sort source zset by target zset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.sortIt = function (params, callback) { | |
var source = params.source; | |
var target = params.target; | |
var start = params.hasOwnProperty('start') ? params.start : 0; | |
var stop = params.hasOwnProperty('stop') ? params.stop : -1; | |
var limit = stop - start + 1; | |
if (limit <= 0) { | |
limit = 0; | |
} | |
var filter = { | |
$or: [{ _key: target }], | |
}; | |
if (params.min !== '-inf' || params.max !== '+inf') { | |
var query = { _key: source }; | |
filter.$or.push(query); | |
if (params.min !== '-inf') { | |
query.score = { $gte: params.min }; | |
} | |
if (params.max !== '+inf') { | |
query.score = { $lte: params.max }; | |
} | |
} | |
var pipeline = [{ $match: filter }]; | |
pipeline.push({ | |
$project: { | |
value: 1, | |
score: { | |
$cond: { | |
if: { | |
$eq: ['$_key', source], | |
}, | |
then: { | |
$multiply: ['$score', 0], | |
}, | |
else: '$score', | |
}, | |
}, | |
}, | |
}); | |
pipeline.push({ $group: { _id: { value: '$value' }, totalScore: { $sum: '$score' }, count: { $sum: 1 } } }); | |
pipeline.push({ $match: { count: 2 } }); | |
pipeline.push({ $sort: { totalScore: -1 } }); | |
if (start) { | |
pipeline.push({ $skip: start }); | |
} | |
if (limit > 0) { | |
pipeline.push({ $limit: limit }); | |
} | |
var project = { _id: 0, _key: 1, value: '$_id.value' }; | |
// project.score = '$totalScore'; | |
pipeline.push({ $project: project }); | |
db.collection('objects').aggregate(pipeline).toArray(function (err, data) { | |
if (err || !data) { | |
return callback(err); | |
} | |
callback(null, data); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment