1

I store millions of price change data for various items in "Price" array in MongoDB like as:

{ 
  "item" : "I1",
  "Price" : [
         {"k": "2020-07-01", "v": [{"t":t1, "v":1000}, {"t":t2, "v":1500}, {"t":t3, "v":1350}, ..]},
         {"k": "2020-07-02", "v": [{"t":t1, "v":1200}, {"t":t2, "v":1250}, {"t":t3, "v":1050}, ..]},         
         ...
     ]
 },
 { 
   "item" : "I2",
   "Price" : [
         {"k": "2020-07-01": [{"t":t1, "v":1025}, {"t":t2, "v":1200}, {"t":t3, "v":1400}, ..]},
         {"k": "2020-07-02": [{"t":t1, "v":1560}, {"t":t2, "v":1050}, {"t":t3, "v":1350}, ..]},
         ...
     ]
 }

I just wondering is there any way to push a new time-price for example {"t": t', "v": 2000} in Price array's element with a specific key, such as "k": "2020-07-01"? The result for item "I1" should be like as:

{ 
  "item" : "I1",
  "Price" : [
         {"k": "2020-07-01", "v": [{"t":t1, "v":1000}, {"t":t2, "v":1500}, {"t":t3, "v":1350}, .., {"t":t', "v":2000}]},
         {"k": "2020-07-02", "v": [{"t":t1, "v":1200}, {"t":t2, "v":1250}, {"t":t3, "v":1050}, ..]},         
         ...
     ]
 },

Thanks

1 Answer 1

2

Yes you can try updateMany() and positional operator $,

db.collection.updateMany(
    { 
      "item": "I1",
      "Price.k": "2020-07-01" 
    },
    {
        $push: {
            "Price.$.v": {
                "t": "t4",
                "v": 2000
            }
        }
    }
)
Sign up to request clarification or add additional context in comments.

5 Comments

I got "batch op errors occurred" error when execute your code! Do you have any idea that where is the problem? @turivishal
can you please provide more details. where and how you are exhibiting this query?
I execute code using pymongo: UpdateOne({where_statement}, {$push:{...}}, upsert=True) @turivishal
I also use bulk_write to write several updates. The problem is with Price.$.v! When I remove $ it works. However, the result is not what I need. @turivishal
I am sure answered query correct, you can check in mongo shell, the problem is from pymongo bulk write, look at this question. sorry i don't know about python, you can ask new question for that.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.