Last active
December 30, 2018 01:23
-
-
Save vulcan25/191bafe82bdc54ec0379c4f05caf05b6 to your computer and use it in GitHub Desktop.
Mongodb counter increment.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 })) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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