Skip to content

Instantly share code, notes, and snippets.

@vulcan25
Last active December 30, 2018 01:23
Show Gist options
  • Save vulcan25/191bafe82bdc54ec0379c4f05caf05b6 to your computer and use it in GitHub Desktop.
Save vulcan25/191bafe82bdc54ec0379c4f05caf05b6 to your computer and use it in GitHub Desktop.
Mongodb counter increment.
from flask import Flask,Response
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World!"
@app.route('/<int:recipe_id>',methods=['GET'])
def home(recipe_id):
# Don't import stuff here, just for demo
import db
posts = db.posts
# increase counter
posts.update({'_id': recipe_id}, {'$inc': {'counter': 1}})
print('Flask says: ', posts.find_one({'_id': recipe_id }))
return Response(status=200)
# run the server
if __name__ == '__main__':
app.run(debug=True)
# Database setup stuff
import pymongo
from pymongo import MongoClient
client = MongoClient()
db = client.test_database
collection = db.test_collection
posts = db.posts
# Count should have been incremented by initial shell session
print('Db script: ', posts.find_one({'_id': 1 }))
# Database setup stuff
>>> import pymongo
>>> from pymongo import MongoClient
>>> client = MongoClient
>>> client = MongoClient()
>>> db = client.test_database
>>> collection = db.test_collection
# Create something and confirm ID
>>> post = {'_id':1, 'text':'TEST', 'counter' : 1 }
>>> posts = db.posts
>>> post_id = posts.insert_one(post).inserted_id
>>> post_id
1
# Search it, second line here returns blank cause nothing with id 2 exists.
>>> posts.find_one({'_id': 1 })
{'_id': 1, 'text': 'TEST', 'counter': 1}
>>> posts.find_one({'_id': 2 })
# Update the counter
>>> posts.update({'_id': 1}, {'$inc': {'counter': 1}})
{'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
# Confirm this worked, counter should be 2
>>> posts.find_one({'_id': 1 })
{'_id': 1, 'text': 'TEST', 'counter': 2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment