简体   繁体   English

MongoDB和PyMongo - 如何在单个文档字段内连接字符串

[英]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" ;). 我是mongoDb的新手,我遇到了字符串字段“增量”的问题;)。 I have the following document in collection "currentactivities": 我在“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" “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. 我使用Python 2.7,PyMongo和MongoDB 3.0。 I tried inserting additional field with new temp string data and using aggregation framwework, but it doesnt work. 我尝试使用新的临时字符串数据插入附加字段并使用聚合framwework,但它不起作用。

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? 任何人都知道如何解决PyMongo中的问题?

Currently you can't use the old value of a document field during an update, see this JIRA ticket. 目前,您无法在更新期间使用文档字段的旧值,请参阅此JIRA票证。 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"}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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