简体   繁体   English

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

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

I am working on building sample data for a school project.我正在为一个学校项目构建样本数据。 I want some of the numbers to look unique.我希望一些数字看起来独一无二。 I have two arrays我有两个 arrays

for_sale_prices = ["$50,000", "$100,000", "$200,000", "$300,000",'$400,000', "$500,000", "$600,000",'$700,000', "$800,000", "$900,000"]
for_rent_prices = ["$60", "$70", "$80", "$90",'$100', "$110", "$120",'$130', "$140", "$150"]

I want to add a price field to every document with a number randomly chosen from the above arrarys.我想为每个文档添加一个价格字段,其中包含从上述数组中随机选择的数字。 I looked into update_many but that gives every document the same price and I tried this...我查看了 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"}
])

which doesn't even create a price field.它甚至没有创建价格字段。 I have yet to find anyone with a similar problem online and would appreciate any guidance.我还没有在网上找到有类似问题的人,希望得到任何指导。

You cannot assign random numbers to each document using one command only except when you iterate over all of them and update them one by one.您不能仅使用一个命令为每个文档分配随机数,除非您遍历所有文档并一一更新它们。 However, you can use the functionality of updating a new field based on the value of a present field.但是,您可以使用根据现有字段的值更新新字段的功能。

What I propose is: You use a dynamic field from the doc itself (let's take description ).我的建议是:您使用文档本身的动态字段(让我们以description )。 Let's calculate it's length and calculate mod(len(description),7) (I took 7, you can take any prime no between 1 to 9 to generate a number ranging from 0 to 9)让我们计算它的长度并计算mod(len(description),7) (我取了 7,你可以取 1 到 9 之间的任何素数来生成一个从 0 到 9 的数字)

Implementation:执行:

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

Also, to add to your other point - Aggregation Projection does not CREATE/UPDATE .另外,补充一点 - 聚合投影不会 CREATE/UPDATE It only projects the new field temporaily in the aggregation result but does not modify the docs它仅在聚合结果中临时投影新字段,但不修改文档

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

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