0

I am working on building sample data for a school project. I want some of the numbers to look unique. I have two 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...

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.

1 Answer 1

1

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). 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)

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. It only projects the new field temporaily in the aggregation result but does not modify the docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.