Skip to content

Instantly share code, notes, and snippets.

@marcellmars
Created November 3, 2013 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcellmars/7288728 to your computer and use it in GitHub Desktop.
Save marcellmars/7288728 to your computer and use it in GitHub Desktop.
mongodb queries, updates, etc.
**filemongodb (letssharebooks collection)**
----------
[TOC]
### start mongodb in docker
sudo docker run -d librarian/mongodb --noprealloc --smallfiles
### get list of authors/titles sorted
authors_sorted= sorted(db.books.find().distinct('authors'))
titles_sorted = sorted(db.books.find().distinct('title_sort'))
### pagination through skip/limit + sort it out
db.books.find().sort("title_sort", 1).skip(256).limit(16)
### find all values in field 'authors' by regex /.*oris.*/
db.books.find({"authors":{"$regex":".*oris.*", "$options": 'i'}})
### regex /.*oris.*/ in multiple fields: 'title', 'authors'
db.books.find({"$or": [{"title": {"$regex": ".*oris.*", "$options": 'i'}}, {"authors":{"$regex":".*oris.*", "$options": 'i'}}]})
### find all items having tunnel in list and sort it by title_sort
db.books.find({'tunnel': {"$in" : [u'55457', u'45345']}}).sort("title_sort", 1)
### update field 'books' with value 7 in document where field 'library_uuid' = u'1' from collection test
db.test.update({'library_uuid':u'1'}, {'$push': {'books': 7}})
### find document where in field 'books' has value 3. get first result and print value of key 'library_uuid'
db.test.find({'books': {'$in': [3] }})[0]['library_uuid']
### add new key 'random' to all documents in collection test
db.test.update({}, {'$set': {'random': random.random()}}, upsert=False, multi=True)
### set key 'tunnel' to '3' and 'books_ids' to list books_ids in test_iter collection if existing if not it creates one
db.test_iter.update({'tunnel': '123'}, {'$set':{'tunnel':'3', 'books_ids':books_ids}}, upsert=True)
### find last item from array 'books_ids' from collection test_iter where key 'tunnel' is '3'
db.test_iter.find({'tunnel': '3'}, {'books_ids':{'$slice':-1}})
### remove last item from array 'books_ids' from collection test_iter where key 'tunnel' is '3'
db.test_iter.update({'tunnel': '3'}, {'$pop':{'books_ids':1}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment