Skip to content

Instantly share code, notes, and snippets.

@yuanchuan
Created November 2, 2012 04:13
Show Gist options
  • Save yuanchuan/3998675 to your computer and use it in GitHub Desktop.
Save yuanchuan/3998675 to your computer and use it in GitHub Desktop.
Experimental problem solving with MongoDB
/**
* Experimental problem solving with MongoDB
*
* 描述:
*
* 假设现在有百万级的数据,每个数据存储着用户的信息(可以是简易的信息),
* 每个数据中含有一个用户的ID,还有一个特殊数据,我们可以将这个数据叫做“等级”。
* 现在 我们的需求是:
* 1,根据一个用户ID能快速找出该用户信息
* 2,根据一个用户ID能快速找出比该用户的“等级”低的最靠近他的10名别的用户,和找出比该用户“等级”高的10名用户
*/
/**
* 初始化测试数据
*/
for (var i = 0; i < 10000; ++i) {
db.test.insert({
id: (''+Math.random()).substr(2),
rank: Math.floor(200*Math.random())
})
}
/**
* 按 id 查找用户
*/
function getUserById(id) {
return db.test.findOne({id: id}) || {};
}
/**
* 查找指定用户的 rank 值
*/
function getRankById(id) {
return getUserById(id).rank;
}
/**
* 查找比用户等级高的用户
*/
function getHigherRankUsersOf(id, maxnum) {
var rank = getRankById(id);
return db.test.find({ rank: {'$gt': rank}}).limit(maxnum || 10);
}
/**
* 查找比用户等级低的用户
*/
function getLowerRankUsersOf(id, maxnum) {
var rank = getRankById(id);
return db.test.find({ rank: {'$lt': rank}}).limit(maxnum || 10);
}
@yuanchuan
Copy link
Author

"最靠近他" 指的是怎样的靠近??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment