Home > front end >  MongoDB update value of deeply nested array and sort
MongoDB update value of deeply nested array and sort

Time:04-14

I have this document of timestamps sorted by time:

{
  _id: '1',
  timestamps: [
    {
      id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
      time: '2022-04-13T19:00:00.122Z'
    },
    {
      id: '781a47de-d21a-4c2c-9814-b46f4a3cfa30',
      time: '2022-04-13T20:00:00.498Z'
    }
  ]
};

I want to update a timestamp by id, change the time, and sort

example: update timestamp with id: '589b32cf-28b3-4a25-8fd1-5e4f86682199':

{
  id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
  time: '2022-04-13T20:30:00.122Z'
}

the updated document should like this:

{
  _id: '1',
  timestamps: [
    {
      id: '32bb3-2222-1111-j878-b4000a3wwa30',
      time: '2022-04-13T19:30:00.122Z'
    },
    {
      id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
      time: '2022-04-13T20:30:00.122Z'
    }
  ]
};

I came up with this method to update and sort each element in the array:

const updateResult = await TimestampCollection.updateOne(
  { _id: '1' },
  {
    $push: {
      timestamps: {
        $each: [{ id: timestamp.id, time: timestamp.time }],
        $sort: { time: 1 }
      }
    }
  }
);

However this pushed a new object to the array with the same id and updated time:

{
  _id: '1',
  timestamps: [
    {
      id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
      time: '2022-04-13T19:00:00.122Z'
    },
    {
      id: '32bb3-2222-1111-j878-b4000a3wwa30',
      time: '2022-04-13T19:30:00.122Z'
    },
    {
      id: '589b32cf-28b3-4a25-8fd1-5e4f86682199',
      time: '2022-04-13T20:30:00.122Z'
    }
  ]
};

Any idea how to fix this?

CodePudding user response:

I didn't find a way to do this in a single query. Sadly combining $set and $push in a single query leads to a conflict...

db.collection.update({
  _id: "1",
  "timestamps.id": timestamp.id
},
{
  "$set": {
    "timestamps.$.time": timestamp.time
  },
});

db.collection.update({
  _id: "1",
},
{
  "$push": {
    "timestamps": {
      "$each": [],
      "$sort": {
        "time": 1
      }
    }
  }
})

This solution involves two queries. One for updating the element in the array and the other for sorting the array.

  • Related