I am trying to update the value of project['submission']['status'] to queued for each matching version as below but running into a compilation error,any pointers on how to fix it is really appreicated?
from pymongo import MongoClient
from bson.objectid import ObjectId
import os,pymongo
dbuser = os.environ.get('muser', '')
dbpass = os.environ.get('mpwd', '')
uri = 'mongodb://{dbuser}:{dbpass}#machineip/data'.format(**locals())
client = MongoClient(uri)
db = client.data
collection = db['test']
print db.version
cursor = collection.find({})
cursor = collection.find({})
for document in cursor:
if document['version'] == '9.130.39.0.32.6.1':
for project in document['projects']:
print project
print project['name']
print project['_id']
id = project['_id']
print project['submission']['status']
if project['submission']['status'] != 'queued':
print "Inside Update.."
#project['submission']['status'] = 'queued'
collection_projects = document['projects']
#print collection_projects
for project in collection_projects:
project.update(
{ "_id": ObjectId(id) },
{
"$set": {
"sanity": "queued"
}
})
Document:
{
"_id" : ObjectId("5a95a1c32a2e2e0025e6d6e2"),
"status" : "Submitting",
"sanity" : "none",
"version" : "9.130.39.0.32.6.1",
"requestTime" : ISODate("2018-02-27T18:21:55.764Z"),
"projects" : [
{
"name" : "BCMFurm_4364_B2_ekans",
"_id" : ObjectId("5a95a1c32a2e2e0025e6d6eb"),
"submission" : {
"status" : "passed", --> this status should change to "queued"
"system" : "machine.com"
}
},
{
"name" : "BCMFurm_4364_B2_sid",
"_id" : ObjectId("5a95a1c32a2e2e0025e6d6ea"),
"submission" : {
"status" : "passed",--> this status should change to "queued"
"system" : "machine.com"
}
},
{
"name" : "BCMFurm_4364_Notes",
"_id" : ObjectId("5a95a1c32a2e2e0025e6d6e3"),
"submission" : {
"status" : "passed",--> this status should change to "queued"
"system" : "machine.com"
}
}
],
"Notes" : [],
}
Error:-
"sanity": "queued"
TypeError: update expected at most 1 arguments, got 2
UPDATE:-
'''
for document in cursor:
if document['version'] == '9.130.39.0.32.6.1':
for project in document['projects']:
print project
project_id = project['_id']
if project['submission']['status'] != 'queued':
project.update(
{ "_id" : ObjectId(project_id)},
{ "$set":
{
"submission.status": "queued"
}
}
)
'''
for document in cursor:
docId = document['_id']
print "docId"
print docId
if document['version'] == '9.130.39.0.32.6.1':
for project in document['projects']:
print "project"
print project
projectId = project['_id']
print "projectId"
print projectId
document.update({ "_id": ObjectId(docId), "projects._id": ObjectId(projectId) },
{
'$set': {
'projects.$.submission.status': 'queued'
}
}
)
Following works,it should be collection.update instead of db.update
for document in cursor:
docId = document['_id']
print "docId"
print docId
if document['version'] == '9.130.39.0.32.6.1':
for project in document['projects']:
print "project"
print project
projectId = project['_id']
print "projectId"
print projectId
collection.update({ "_id": ObjectId(docId), "projects._id": ObjectId(projectId) },
{
'$set': {
'projects.$.submission.status': 'queued'
}
}
)
Try:
for project in document['projects']:
print project
print project['name']
print project['_id']
id = project['_id']
print project['submission']['status']
if project['submission']['status'] != 'queued':
print "Inside Update.."
project.update({"sanity": "queued"})
This will add the property "sanity":"queued" to the project in the loop. Is that what you want?
The value to the key "projects" is a list, not a dictionary. You need to append your new list:
collection_projects.append([
{ "_id": ObjectId(id) },
{
"$set": {
"sanity": 'queued'
}])
And change the syntax as such.
You have to update your document.
var docId = document._id;
var projectId = project._id;
document.update({ "_id": ObjectId(docId), "projects._id": ObjectId(projectId) },
{
'$set': {
'projects.$.submission.status': 'queued'
}
}
);
This should work.
You can also iterate all the projects assign the status and at the end of iteration update the whole document at once, this will also work.
Related
I'm trying to get my Flask server to update to a Mongo Atlas DB on request. When a request is passed with the required arguments, it will post to a Discord webhook then attempt to update DB values.
Example: Going to https://(redacted for privacy)/(redacted for privacy)?iid=123&username=wow&price=22 with JUST the webhook code (doesn't touch DB) will do this:
(sent to discord webhook) and give a success message (outputs as 200 in the console).
But when I enable the DB code, the same link will through a 500 error. Anything I can do? The console outputs as;
balance = mycol.find_one({"UserID": uid})['balance']
TypeError: 'NoneType' object is not subscriptable
I don't understand why this won't work. Here's the code that works, but only posts to the webhook (commented stuff is DB related):
#balance = mycol.find_one({"UserID": uid})['balance']
#res = mycol.find_one({"UserID": uid})
#newvalues = { "$set": { "UserID": uid, "balance": int(balance) + int(cashback_amt)} }
#mycol.update_one(res, newvalues)
img_url = f"https://www.roblox.com/bust-thumbnail/image?userId={uid}&width=420&height=420&format=png"
data = {
"content" : "**New purchase!**",
"username" : "robate"
}
data["embeds"] = [
{
"description" : f"**ItemID**: `{item_id}`\n**Item Price**: `{price}`\n**Item Cashback**: `{cashback_amt}`",
"title" : "New purchase made",
"color": 65311,
"thumbnail": {"url": img_url}
}
]
result = requests.post(purclog, json = data)
return jsonify({"res": True})
And the non-working DB included code:
balance = mycol.find_one({"UserID": uid})['balance']
res = mycol.find_one({"UserID": uid})
newvalues = { "$set": { "UserID": uid, "balance": int(balance) + int(cashback_amt)} }
mycol.update_one(res, newvalues)
img_url = f"https://www.roblox.com/bust-thumbnail/image?userId={uid}&width=420&height=420&format=png"
data = {
"content" : "**New purchase!**",
"username" : "robate"
}
data["embeds"] = [
{
"description" : f"**ItemID**: `{item_id}`\n**Item Price**: `{price}`\n**Item Cashback**: `{cashback_amt}`",
"title" : "New purchase made",
"color": 65311,
"thumbnail": {"url": img_url}
}
]
result = requests.post(purclog, json = data)
return jsonify({"res": True})
Any help is severely appreciated. Have a good day!
EDIT: The UserID is defined here:
try:
uid = requests.get(f"https://api.roblox.com/users/get-by-username?username={username}").json()['Id']
except:
return
balance = mycol.find_one({"UserID": uid})['balance']
I am trying to update a value of an array stored in a mongodb collection
any_collection: {
{
"_id": "asdw231231"
"values": [
{
"item" : "a"
},
{
"item" : "b"
}
],
"role": "role_one"
},
...many similar
}
the idea is that I want to access values and edit a value with the following code that I found in the mongodb documentation
conn.any_collection.find_one_and_update(
{
"_id": any_id,
"values.item": "b"
},
{
"$set": {
"values.$.item": "new_value" # here the error, ".$."
}
}
)
This should work, but I can't understand what the error is or what is the correct syntax for pymongo. The error is generated when adding "$";
It works fine with my fastAPI.
#app.get("/find/{id}")
async def root(id: int):
db = get_database()
q = {'_id': 'asdw231231','values.item': 'b'}
u = {'$set': {'values.$.item': 'new_value' }}
c = db['any'].find_one_and_update(q, u)
return {"message": c}
mongoplayground
I have below sample data in JSON format :
project_cost_details is my database result set after querying.
{
"1": {
"amount": 0,
"breakdown": [
{
"amount": 169857,
"id": 4,
"name": "SampleData",
"parent_id": "1"
}
],
"id": 1,
"name": "ABC PR"
}
}
Here is full json : https://jsoneditoronline.org/?id=2ce7ab19af6f420397b07b939674f49c
Expected output :https://jsoneditoronline.org/?id=56a47e6f8e424fe8ac58c5e0732168d7
I have this sample JSON which i created using loops in code. But i am stuck at how to convert this to expected JSON format. I am getting sequential changes, need to convert to tree like or nested JSON format.
Trying in Python :
project_cost = {}
for cost in project_cost_details:
if cost.get('Parent_Cost_Type_ID'):
project_id = str(cost.get('Project_ID'))
parent_cost_type_id = str(cost.get('Parent_Cost_Type_ID'))
if project_id not in project_cost:
project_cost[project_id] = {}
if "breakdown" not in project_cost[project_id]:
project_cost[project_id]["breakdown"] = []
if 'amount' not in project_cost[project_id]:
project_cost[project_id]['amount'] = 0
project_cost[project_id]['name'] = cost.get('Title')
project_cost[project_id]['id'] = cost.get('Project_ID')
if parent_cost_type_id == cost.get('Cost_Type_ID'):
project_cost[project_id]['amount'] += int(cost.get('Amount'))
#if parent_cost_type_id is None:
project_cost[project_id]["breakdown"].append(
{
'amount': int(cost.get('Amount')),
'name': cost.get('Name'),
'parent_id': parent_cost_type_id,
'id' : cost.get('Cost_Type_ID')
}
)
from this i am getting sample JSON. It will be good if get in this code only desired format.
Also tried this solution mention here : https://adiyatmubarak.wordpress.com/2015/10/05/group-list-of-dictionary-data-by-particular-key-in-python/
I got approach to convert sample JSON to expected JSON :
data = [
{ "name" : "ABC", "parent":"DEF", },
{ "name" : "DEF", "parent":"null" },
{ "name" : "new_name", "parent":"ABC" },
{ "name" : "new_name2", "parent":"ABC" },
{ "name" : "Foo", "parent":"DEF"},
{ "name" : "Bar", "parent":"null"},
{ "name" : "Chandani", "parent":"new_name", "relation": "rel", "depth": 3 },
{ "name" : "Chandani333", "parent":"new_name", "relation": "rel", "depth": 3 }
]
result = {x.get("name"):x for x in data}
#print(result)
tree = [];
for a in data:
#print(a)
if a.get("parent") in result:
parent = result[a.get("parent")]
else:
parent = ""
if parent:
if "children" not in parent:
parent["children"] = []
parent["children"].append(a)
else:
tree.append(a)
Reference help : http://jsfiddle.net/9FqKS/ this is a JavaScript solution i converted to Python
It seems that you want to get a list of values from a dictionary.
result = [value for key, value in project_cost_details.items()]
i have a payload as shown below which is stored in mongodb
{
"_id" : ObjectId("5865fbf5558b670ac091c81e"),
"sensors" : [
{
"sensorStatus" : "green ",
"sensorName" : "s1"
},
{
"sensorStatus" : "red ",
"sensorName" : "s2"
}
],
"camera" : [
{
"cameraName" : "cam1",
"cameraStatus" : "live"
},
{
"cameraName" : "cam2",
"cameraStatus" : "live"
}
],
"checkpoints" : [
{
"checkPointName" : "chk1"
}
]
}
trying to write route to display this data as shown below
#gateway_bp.route('/gateway',methods=['GET'])
def list_gateWay():
gateways = Gateway.query.all()
print gateways
return Response(json.dumps(gateways), mimetype='application/json')
i am getting the error has
TypeError: <app.model.canvasmodel.Gateway object at 0x02E99D10> is not JSON serializable
the schema is as shown below
from app.dbconfig.extensions import db
class Sensors(db.Document):
sensorName = db.StringField()
sensorStatus = db.StringField()
class Camera(db.Document):
cameraName = db.StringField()
cameraStatus = db.StringField()
class Checkpoints(db.Document):
checkPointName = db.StringField()
class Gateway(db.Document):
sensors = db.ListField(db.DocumentField(Sensors), db_field='sensors')
camera = db.ListField(db.DocumentField(Camera), db_field='camera')
checkpoints = db.ListField(db.DocumentField(Checkpoints), db_field='checkpoints')
please help to correct the get request thanks
Does anyone know, how I can implement the following MongoDB query using a MongoEngine Raq-Query?
db.getCollection('subscribers').find({
'_id': ObjectId("579e60b0c525fd2037e8dd31"),
'history.content.read_process_msg': {
'$exists':true
},
'history.content.read_processed': {
'$exists':true
},
'history.content.read_processed': false
},
{'history.$':1})
I read, that the raw-query doesn't support projections and that one should use .only() instead. But the problem here is, that it returns all the empty documents also…
Any advice?
Edit: Here are my models and a sample document:
class Subscriber(Document):
service = StringField()
history = EmbeddedDocumentListField('SubscriberHistory')
def __str__(self):
return self.service
class SubscriberHistory(EmbeddedDocument):
action = StringField()
content = DictField()
def __str__(self):
return self.action
And the sample:
{
"_id" : ObjectId("579e60b0c525fd2037e8dd31"),
"service" : "foo",
"history" : [
{
"action" : "outbound",
"content" : {
"read_processed" : false,
"message_data" : {
"text" : "w00t?"
},
"read_process_msg" : {
"$ref" : "bots_messages",
"$id" : ObjectId("57a6529dc525fd8066ee25b3")
}
},
"created_at" : ISODate("2016-08-06T21:12:00.986Z")
}
]
}