3

Im new to mongoDb, and i'm stuck with a problem with string field "incrementation" ;). I have the following document in collection "currentactivities":

document={
    "name": "App  Name",
    "total Active": "10",
    "total Inactive": "60"
    "data": "Some data generated by app: 2ndkjasndu2iqeqjsma" 
}

I want to append the "data" field, with new additional string values many times a day, for example with data such as:

"njsadklfu3j2n1km121"

so after update the document should look like:

document={
    "name": "App  Name",
    "total Active": "10",
    "total Inactive": "60"
    "data": "Some data generated by app: 2ndkjasndu2iqeqjsmanjsadklfu3j2n1km121" 
}

Im using Python 2.7, with PyMongo and MongoDB 3.0. I tried inserting additional field with new temp string data and using aggregation framwework, but it doesnt work.

currentactivities.update(
    {"name": "App Name"},
    {"$set": {"dataNew": "njsadklfu3j2n1km121"}
     }, upsert=True)

pipeline = [
        { "$project":
              {
                  "name":1,
                  "total Active":1,
                  "total Inactive":1,
                  "data": {"$concat": ["$data" , "$dataNew"] }
              }
        }
]
list(currentactivities.aggregate(pipeline))

I cannot download the field value, concat the string on client side, because the whole "data" field will contain too much data to send between client <> server. I want only to push differences to be added to the data field. Anyone knows how to solve that problem in PyMongo?

  • If I understand you want to update your document with the new "data" value. right? Do you want to unset the "dataNew" field after the update operation? What to do with documents where "data" is absent? Any particular reason you using `upsert=True` – styvane Dec 14 '15 at 06:13

1 Answers1

2

Currently you can't use the old value of a document field during an update, see this JIRA ticket. You will have to cursor through the records and update the records one by one. For example:

cursor = currentactivities.find({"name": "App Name"})

for document in cursor:
    currentactivities..update_one({"_id": document["_id"]},
   {"$set": {"dataNew": document["data"]+ "njsadklfu3j2n1km121"}}
Alex
  • 21,273
  • 10
  • 61
  • 73