Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # basic search
- ```javascript
- db.getCollection('collection_1').find({});
- ```
- # projection
- ```javascript
- db.getCollection('collection_1').find({}, {'_id': 1});
- ```
- # limit
- ```javascript
- db.getCollection('collection_1').find({}, {'_id': 1}).limit(10);
- ```
- # count
- ```javascript
- db.getCollection('collection_1').find({}).count();
- ```
- # remove
- ```javascript
- db.getCollection('collection_1').remove({'_id': ObjectId('xxxxxxxxxx')});
- ```
- # pattern search
- ```javascript
- db.getCollection('collection_1').find({'field_1': {'$regex': 'pattern'}})
- db.getCollection('collection_1').find({'field_1': {'$regex': 'pattern', '$options': 'i'}})
- ```
- # time search
- ```javascript
- function objectIdWithTimestamp(timestamp) {
- // Convert string date to Date object (otherwise assume timestamp is a date)
- if (typeof(timestamp) == 'string') {
- timestamp = new Date(timestamp);
- }
- // Convert date object to hex seconds since Unix epoch
- var hexSeconds = Math.floor(timestamp/1000).toString(16);
- // Create an ObjectId with that hex timestamp
- var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
- return constructedObjectId
- }
- db.getCollection('collection_1').find({'_id': {$gt: objectIdWithTimestamp('2017/11/04')}});
- ```
- # filter elements where field_1 exists
- ```javascript
- db.getCollection('collection_1').find({'field_1': {'$exists': 1}})
- ```
- # filter elements if field in or not in list
- ```javascript
- db.getCollection('collection_1').find({'field_1': {'$in': []}})
- db.getCollection('collection_1').find({'field_1': {'$nin': []}})
- db.getCollection('collection_1').find({'_id': {'$in': [ObjectId('xxxxxxxxxx'), ObjectId('xxxxxxxxxx') ]}})
- ```
- # group by
- ```javascript
- db.getCollection('collection_1').remove({'_id': ObjectId('xxxxxxxxxx')});
- ```
- # group by advanced example
- ```javascript
- db.getCollection('collection_1').aggregate([
- {'$unwind': '$field_1'},
- {'$unwind': '$field_1.sub_field_1'},
- {'$project': {'new_field_1_name': '$field_1.sub_field_1', '_id': 1}},
- {'$group': { _id: null, count: {'$sum': 1}}}
- ])
- ```
- # copy elements to another collection
- ```javascript
- db.getCollection('collection_1').find().forEach(function(doc){
- db.getCollection('collection_2').insert(doc);
- });
- ```
Add Comment
Please, Sign In to add comment