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

Asef Pourmasoomi
  • 464
  • 1
  • 3
  • 17

1 Answers1

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
            }
        }
    }
)
turivishal
  • 34,368
  • 7
  • 36
  • 59
  • I got "batch op errors occurred" error when execute your code! Do you have any idea that where is the problem? @turivishal – Asef Pourmasoomi Sep 01 '20 at 15:25
  • can you please provide more details. where and how you are exhibiting this query? – turivishal Sep 01 '20 at 15:39
  • I execute code using pymongo: UpdateOne({where_statement}, {$push:{...}}, upsert=True) @turivishal – Asef Pourmasoomi Sep 02 '20 at 04:21
  • 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 – Asef Pourmasoomi Sep 02 '20 at 04:32
  • I am sure answered query correct, you can check in mongo shell, the problem is from pymongo bulk write, look at this [question](https://stackoverflow.com/questions/30355790/mongodb-bulk-write-error). sorry i don't know about python, you can ask new question for that. – turivishal Sep 02 '20 at 04:43