Guest User

Untitled

a guest
Aug 16th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. private const string host = "mongodb://localhost/";
  2.  
  3. static void Main(string[] args)
  4. {
  5. MongoServer server = MongoServer.Create(host);
  6.  
  7. MongoDatabase test = server.GetDatabase("testDB");
  8.  
  9. List<int> list = Enumerable.Range(0, 100000).ToList();
  10.  
  11.  
  12. using (server.RequestStart(test))
  13. {
  14. MongoCollection coll = test.GetCollection("testCollection");
  15.  
  16. server.IndexCache.Add(coll, "_id_");
  17.  
  18. List<BsonValue> b = list.Select(l => BsonValue.Create(l)).ToList();
  19. var q = Query.In("_id", b);
  20.  
  21. var found = coll.FindAs<BsonDocument>(q);
  22. found.SetFields(new[] {"_id"});
  23.  
  24. DateTime start = DateTime.Now;
  25. var f = found.AsParallel().Select(fo => fo["_id"].AsInt32).ToList();
  26.  
  27. Console.WriteLine(string.Format("Found {0} docs", f.Count));
  28. List<BsonDocument> documents = list.Except(f).Select(item => new BsonDocument { { "_id", item }, { "value", list[item] + list[item] } }).ToList();
  29. var updateDocs = list.Intersect(f);
  30.  
  31. Console.WriteLine(string.Format("starting threads"));
  32.  
  33. ThreadStart ts = () =>
  34. {
  35. documents = documents.AsParallel().Where(d => d != null).ToList();
  36. Console.WriteLine(string.Format("inserting {0} documents",documents.Count));
  37. coll.InsertBatch(documents, SafeMode.False);
  38. };
  39. Thread t = new Thread(ts);
  40.  
  41.  
  42. ThreadStart update = () => Parallel.ForEach(updateDocs, i =>
  43. {
  44. var query = new QueryDocument("_id", i);
  45. coll.Update(query,
  46. Update.Set("value", i+i),
  47. SafeMode.False);
  48. });
  49. Thread up = new Thread(update);
  50.  
  51. up.Start();
  52. t.Start();
  53.  
  54. t.Join();
  55. up.Join();
  56.  
  57. DateTime end = DateTime.Now;
  58. Console.WriteLine(string.Format("Wrote {0} lines in {1}ms", list.Count, end.Subtract(start).TotalMilliseconds));
  59. }
  60.  
  61.  
  62. }
Add Comment
Please, Sign In to add comment