0

I'd like to know the best approach to do a count over a list that is part of a collection, for simplicity I've abstracted to the following model:

public class User
{
    [BsonId]
    public ObjectId Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<ObjectId> Followers { get; set; }
    public List<ObjectId> Following { get; set; }  
}

Just assume that probably the average of followers/ following could be around 2k on each property, I know some people like to pre-calculate the information using inc, is that recommend under the circumstances described above? if that's the case which could be the approach using the C# driver?

i3arnon
  • 113,022
  • 33
  • 324
  • 344
pedrommuller
  • 15,741
  • 10
  • 76
  • 126

1 Answers1

0

If you have a large number of users (say millions) and you query on this count frequently, why not use a map reduce? From the c# driver you could read the results of the map reduce.

If you have a small number of users (1000s), you could probably use the aggregation framework on demand, depending on how fast you need the query to be. See an example here Mongo order by length of array. From the c# driver you could execute the aggregation

If you decide to denormalize the count on saves, you can run a migration from the mongo shell to create the initial values via a cursor. See my answer about these types of migrations MongoDB: schema migration, update or insert

Community
  • 1
  • 1
Wes
  • 711
  • 7
  • 6
  • In this case I'd have maybe 500k to 1M of users, but the followers / following could be arround 200 ~ 2k aprox per user, in the case of making a query of a single user to me makes sense to perform a length of array...what do you think? – pedrommuller Jan 03 '14 at 14:28
  • Are you only querying this for one user for say their profile page? Or are you querying across your 500K users? – Wes Jan 03 '14 at 18:07
  • I'm querying across the 500k but I'm only retrieving only one document per ID, then I need to do the count for following / followers – pedrommuller Jan 03 '14 at 23:51
  • 1
    Ok so you aren't querying on the count? If so then you can do the count after the document has been deserialized to your c# model using [Array.Length](http://msdn.microsoft.com/en-us/library/system.array.length(v=vs.110).aspx) – Wes Jan 05 '14 at 00:23