MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come si progetta uno schema MongoDB per un aggregatore di articoli di Twitter

due consigli generali:1.) non aver paura di duplicare. È spesso una buona idea archiviare gli stessi dati formattati in modo diverso in raccolte diverse.

2.) se vuoi ordinare e riassumere le cose, aiuta a tenere i campi di conteggio ovunque. Il metodo di aggiornamento atomico di mongodb, insieme ai comandi upsert, semplifica il conteggio e l'aggiunta di campi ai documenti esistenti.

Quanto segue è sicuramente imperfetto perché è digitato dalla parte superiore della mia testa. Ma meglio cattivi esempi che nessun esempio ho pensato;)

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
   }
}

aggiungi nuovo tweet:

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);

Ottenere i primi dieci link ordinati per numero di tweet che hanno?

db.x.links.find().sort({'totalCount:-1'}).limit(10);

Ricevi il link più twittato per una data specifica?

db.x.links.find({'$gt':{'daycount.123413453':0}}).sort({'daycount.123413453':-1}).limit(1); //123413453 is the day you're after

Ricevi i tweet per un link?

db.x.tweets.find({'links': 'http://lin.k'});

Ricevi gli ultimi dieci tweet?

db.x.tweets.find().sort({'timeTweeted': -1}, -1).limit(10);