Update an array into One Document

Hi

i am new to mongodb and will like to get some help.

i wish to store a json which contains array of “records” in one document.
E.g. one document called “UK”, which contains top 20 records of temperature. i am writing in python.

When i try to update the record using update,
.update({“date”: “06-05-2021”, “temp”: 10, }, {“date”: “07-05-2021”, “temp”: 11 }, upsert=True)
, there will also be multiple records created (despite using upsert ) with new id, and also the values in each record contains only 1 value.

I also encountered issue when i try to use a converted json which a list of records in python which i encountered “more than 1 parameter is required” issue. Please advise. thank you

Hi @Chun_Leong_Lee,

You need to use a filter + $push command to an array:

> db.temp.update({"country" : "US"},{$push : { temperature  : {"date": "07-05-2021", "temp": 11 }}}, {upsert : true});
{
  acknowledged: true,
  insertedId: { index: 0, _id: ObjectId("6093c45f14febd9ff2772ead") },
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}
> db.temp.update({"country" : "US"},{$push : { temperature  : {"date": "06-05-2021", "temp": 10 }}}, {upsert : true});
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
> db.temp.find({})
[
  {
    _id: ObjectId("6093c45f14febd9ff2772ead"),
    country: 'US',
    temperature: [
      { date: '07-05-2021', temp: 11 },
      { date: '06-05-2021', temp: 10 }
    ]
  }
]

The filter make sure that if upserted the document has a “country” field and the $push insert a document in an array if it is matched … Now if you wish to have only top 20 you can use a $each and $slice like that:

 db.temp.update({"country" : "US"},{$push : { temperature  : { $each : [{"date": "05-05-2021", "temp": 10 }], $sort : {date : -1}, $slice: 20}}}, {upsert : true});

Porting this to python should be fairly easy:

Thanks
Pavel

1 Like