两个一般提示:
1.)不要害怕重复。将相同的数据以不同的格式存储在不同的集合中通常是一个好主意。
2.) 如果你想对东西进行排序和总结,它有助于在任何地方保留计数字段。 mongodb 的原子更新方法与 upsert 命令一起可以轻松统计并向现有文档添加字段。
下面的内容肯定是有缺陷的,因为它是我凭空想出来的。但我认为坏例子总比没有例子好;)
colletion tweets:
{
tweetid: 123,
timeTweeted: 123123234, //exact time in milliseconds
dayInMillis: 123412343, //the day of the tweet kl 00:00:00
text: 'a tweet with a http://lin.k and an http://u.rl',
links: [
'http://lin.k',
'http://u.rl'
],
linkCount: 2
}
collection links:
{
url: 'http://lin.k'
totalCount: 17,
daycounts: {
1232345543354: 5, //key: the day of the tweet kl 00:00:00
1234123423442: 2,
1234354534535: 10
}
}
添加新推文:
db.x.tweets.insert({...}) //simply insert new document with all fields
//for each found link:
var upsert = true;
var toFind = { url: '...'};
var updateObj = {'$inc': {'totalCount': 1, 'daycounts.12342342': 1 } }; //12342342 is the day of the tweet
db.x.links.update(toFind, updateObj, upsert);
获取按推文数量排序的前十个链接?
db.x.links.find().sort({'totalCount:-1'}).limit(10);
获取特定日期推文最多的链接?
db.x.links.find({'$gt':{'daycount.123413453':0}}).sort({'daycount.123413453':-1}).limit(1); //123413453 is the day you're after
获取推文的链接?
db.x.tweets.find({'links': 'http://lin.k'});
获取十条最新推文?
db.x.tweets.find().sort({'timeTweeted': -1}, -1).limit(10);