MongoDB Shell Commands


/ Published in: JavaScript
Save to your folder(s)

MongoDB


Copy this code and paste it in your HTML
  1. makeId = function (doc) {
  2. var id = Math.floor(Math.random() * 900000) + 100000, that = this; // max(900000)/min(100000)
  3. var key = "", i, v, that = this;
  4.  
  5. for (i = 0; i < 32; i++) {
  6. v = Math.random() * 16 | 0;
  7.  
  8. if (i == 8 || i == 12 || i == 16 || i == 20) {
  9. key += '-';
  10. }
  11.  
  12. if (i == 12) {
  13. key += '4';
  14. } else {
  15. key += (i == 16 ? (v & 3 | 8) : v).toString(16);
  16. }
  17. }
  18.  
  19. var res = db.users.findOne({$or: [
  20. {id: id},
  21. {key: key}
  22. ]});
  23.  
  24. if(res) {
  25. makeId(doc);
  26. } else {
  27. doc.id = id;
  28. doc.key = key;
  29. db.users.save(doc);
  30.  
  31. print(id);
  32. }
  33. }
  34.  
  35. db.users.ensureIndex({id:1},{unique:true,sparse:true})
  36. db.users.ensureIndex({key:1},{unique:true,sparse:true})
  37.  
  38. db.users.find().limit(10).forEach(function(doc){ makeId(doc); })
  39.  
  40.  
  41.  
  42. db.friends.find().limit(100000).forEach(function (doc) {
  43. var user = db.users.findOne({mysql_id: doc.user2});
  44. var friend = db.users.findOne({mysql_id: doc.user1});
  45.  
  46. if (user && friend) {
  47. if (!(db.users.findOne({mysql_id: doc.user2, followers: friend._id}))) {
  48. user.followers.push(friend._id);
  49. db.users.save(user);
  50.  
  51. print(friend._id);
  52. }
  53. }
  54. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.