如何使用pymongo中的唯一值更新每个文档中的元素

How to update an element in every document with a unique value in pymongo

我正在为一个学校项目构建样本数据。我想让一些数字看起来独一无二。我有两个数组

for_sale_prices = [",000", "0,000", "0,000", "0,000",'0,000', "0,000", "0,000",'0,000', "0,000", "0,000"]
for_rent_prices = ["", "", "", "",'0', "0", "0",'0', "0", "0"]

我想用从上述数组中随机选择的数字为每个文档添加一个价格字段。我查看了 update_many,但每份文件的价格都相同,我尝试了这个...

for_sale.aggregate([
    { "$project": {
                      "_id": True, 
                      "name": True,
                      "description": True,
                      "picture_url": True,
                      "host_name": True,
                      "neighbourhood": True,
                      "location": True,
                      "bathrooms_text": True,
                      "bedrooms": True,
                      "amenities": True,
                      "price": for_sale_prices[random.randint(0,9)]
                  }
    }, 
    { "$out": "for_sale"}
])

它甚至不创建价格字段。我还没有在网上找到有类似问题的人,希望得到任何指导。

您不能仅使用一个命令为每个文档分配随机数,除非您遍历所有文档并逐一更新它们。 但是,您可以使用根据现有字段的值更新新字段的功能。

我的建议是:使用文档本身的动态字段(让我们采用 description)。让我们计算它的长度并计算 mod(len(description),7)(我取了7,你可以取1到9之间的任意素数生成0到9的数)

实施:

for_sale.update_many(filter={},update={'$set':{'price': {'$mod': [{'$strLenCP' : '$description'}, 7]}}})

此外,要补充您的另一点 - 聚合投影 不 CREATE/UPDATE。它只是在聚合结果中临时投影新字段,但不修改文档