简体   繁体   中英

How to add length of one array field into another field in Mongodb document

I am a newbie in Mongodb. My Mongodb version is v4.4.2. I create a collection in Mongo and want to update one record each time. I receive this record and search collection, if the record is in the collection before, I update that. Unless, I insert the record.

dic = {"CST_NUM": "7101",
       "CNT_TRX_WEEK": 0.224,
       "cities": {"G": {"t": 6, "f": 0},
                  "K": {"t": 4, "f": 0}, "S": {"t": 1, "f": 0}},
       "cst_trm": ["123", "342"]
       }

Also, each record has an array field that when it updated, I must add the size of the array field into another field of the record. Its name is "cst_trm_cnt". I update the collection with this code:

  mycollection.update_one(
 {"CST_NUM": dic["CST_NUM"]},
        {
            "$inc": {"CNT_TRX_WEEK": +dic["CNT_TRX_WEEK"],"cities.S.t": +dic["cities"]["S"]["t"]},
         "$addToSet": { "cst_trm": {"$each":dic["cst_trm"]}},
            "$addfield": {"cst_trm_cnt": {"$size":"cst_trm"}}
        }
    )  

But, I receive this error in the last line of the above code:

 pymongo.errors.WriteError: Unknown modifier: $addfield. Expected a valid update modifier or pipeline-style update specified as an array, full error: {'index': 0, 'code': 9, 'errmsg': 'Unknown modifier: $addfield. Expected a valid update modifier or pipeline-style update specified as an array'}

Would you please guide me how to add length of the array into another field of the record in Mongo?

Any help is really appreciated.

Problem solved. After Updating, in the code, I must add name of the collection, which I have already made,in $out part,unless Mongo builds a new collection. The code is in following:

 mytable.aggregate([
             {"$addFields": {"cst_trm_cnt":{"$size":"$cst_trm"}}},
             {"$out": "test"}
                   ])

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