Skip to content

Instantly share code, notes, and snippets.

@arthuralvim
Last active November 21, 2017 13:44
Show Gist options
  • Save arthuralvim/935f7b82db8ea78249aa2eafda6dfad5 to your computer and use it in GitHub Desktop.
Save arthuralvim/935f7b82db8ea78249aa2eafda6dfad5 to your computer and use it in GitHub Desktop.
MongoDB Snippets

basic search

db.getCollection('collection_1').find({});

projection

db.getCollection('collection_1').find({}, {'_id': 1});

limit

db.getCollection('collection_1').find({}, {'_id': 1}).limit(10);

count

db.getCollection('collection_1').find({}).count();

remove

db.getCollection('collection_1').remove({'_id': ObjectId('xxxxxxxxxx')});

pattern search

db.getCollection('collection_1').find({'field_1': {'$regex': 'pattern'}})
db.getCollection('collection_1').find({'field_1': {'$regex': 'pattern', '$options': 'i'}})

time search

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

db.getCollection('collection_1').find({'field_1': {'$exists': 1}})

filter elements if field in or not in list

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

db.getCollection('collection_1').remove({'_id': ObjectId('xxxxxxxxxx')});

group by advanced example

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

db.getCollection('collection_1').find().forEach(function(doc){
    db.getCollection('collection_2').insert(doc);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment