Guest User

Untitled

a guest
Nov 22nd, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. # basic search
  2.  
  3. ```javascript
  4. db.getCollection('collection_1').find({});
  5. ```
  6.  
  7. # projection
  8.  
  9. ```javascript
  10. db.getCollection('collection_1').find({}, {'_id': 1});
  11. ```
  12.  
  13. # limit
  14.  
  15. ```javascript
  16. db.getCollection('collection_1').find({}, {'_id': 1}).limit(10);
  17. ```
  18.  
  19. # count
  20.  
  21. ```javascript
  22. db.getCollection('collection_1').find({}).count();
  23. ```
  24.  
  25. # remove
  26.  
  27. ```javascript
  28. db.getCollection('collection_1').remove({'_id': ObjectId('xxxxxxxxxx')});
  29. ```
  30.  
  31. # pattern search
  32.  
  33. ```javascript
  34. db.getCollection('collection_1').find({'field_1': {'$regex': 'pattern'}})
  35. db.getCollection('collection_1').find({'field_1': {'$regex': 'pattern', '$options': 'i'}})
  36. ```
  37.  
  38. # time search
  39.  
  40. ```javascript
  41. function objectIdWithTimestamp(timestamp) {
  42. // Convert string date to Date object (otherwise assume timestamp is a date)
  43. if (typeof(timestamp) == 'string') {
  44. timestamp = new Date(timestamp);
  45. }
  46.  
  47. // Convert date object to hex seconds since Unix epoch
  48. var hexSeconds = Math.floor(timestamp/1000).toString(16);
  49.  
  50. // Create an ObjectId with that hex timestamp
  51. var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
  52.  
  53. return constructedObjectId
  54. }
  55.  
  56. db.getCollection('collection_1').find({'_id': {$gt: objectIdWithTimestamp('2017/11/04')}});
  57. ```
  58.  
  59. # filter elements where field_1 exists
  60.  
  61. ```javascript
  62. db.getCollection('collection_1').find({'field_1': {'$exists': 1}})
  63. ```
  64.  
  65. # filter elements if field in or not in list
  66.  
  67. ```javascript
  68. db.getCollection('collection_1').find({'field_1': {'$in': []}})
  69. db.getCollection('collection_1').find({'field_1': {'$nin': []}})
  70. db.getCollection('collection_1').find({'_id': {'$in': [ObjectId('xxxxxxxxxx'), ObjectId('xxxxxxxxxx') ]}})
  71. ```
  72.  
  73. # group by
  74.  
  75. ```javascript
  76. db.getCollection('collection_1').remove({'_id': ObjectId('xxxxxxxxxx')});
  77. ```
  78.  
  79. # group by advanced example
  80.  
  81. ```javascript
  82. db.getCollection('collection_1').aggregate([
  83. {'$unwind': '$field_1'},
  84. {'$unwind': '$field_1.sub_field_1'},
  85. {'$project': {'new_field_1_name': '$field_1.sub_field_1', '_id': 1}},
  86. {'$group': { _id: null, count: {'$sum': 1}}}
  87. ])
  88. ```
  89.  
  90. # copy elements to another collection
  91.  
  92. ```javascript
  93. db.getCollection('collection_1').find().forEach(function(doc){
  94. db.getCollection('collection_2').insert(doc);
  95. });
  96. ```
Add Comment
Please, Sign In to add comment