简体   繁体   中英

MongoDB and PyMongo - how to concat string inside single document field

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?

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"}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM