SA Master
SA Master

Reputation: 57

How to add new fields to the last object in an array in MongoDB?

I have an Array of objects in mongoDB as follow

enter image description here

Initially there is only the heartRate field inside the object. Now I want to add new fields to this object along with the existing heartRate field. Also there can be multiple objects inside the dailyReadings array. Therefore, I need to add new fields only to the last object using nodejs and expressjs

I tried using the $push method but ended up adding new object intead of adding the fields to the last object. Is there a way to achieve this? Thanks in advance!


Why I am doing this (For further understanding):-

I have developed a mobile app to read the heart rate. Initially it will save the heart rate in the database as a new object (As in the image). Then, there are several other data sent through a desktop application which needs to add to the same object (Which is the last object in the dailyReadings array)

Upvotes: 1

Views: 168

Answers (2)

turivishal
turivishal

Reputation: 36104

There is no straight way to do this, you can try update with aggregation pipeline starting from MongoDB 4.2,

  • $size to get total elements in dailyReadings array
  • $subtract to minus 1 from above total elements
  • $slice to get elements other than the last object element
  • $slice to get last object element by -1 from dailyReadings
  • $arrayElemAt to select first object element from array
  • $mergeObjects to merge existing object fields of the last object and new fields that you want to insert
  • $concatArrays to concat first slice array and second updated object
db.collection.update(
  {}, // put your query condition
  [{
    $set: {
      dailyReadings: {
        $concatArrays: [
          {
            $slice: [
              "$dailyReadings",
              0,
              { $subtract: [{ $size: "$dailyReadings" }, 1] }
            ]
          },
          [
            {
              $mergeObjects: [
                { $arrayElemAt: [{ $slice: ["$dailyReadings", -1] }, 0] },
                {
                  newField: "1"
                }
              ]
            }
          ]
        ]
      }
    }
  }]
)

Playground

Upvotes: 1

Devanshu Kumar Singh
Devanshu Kumar Singh

Reputation: 44

In order for you to add fields to the last object, the heartRate should be an object with a schema containing the following

  • Array (for you to add to)
  • any other necessary data type you'd want the object to have

you must define a complex schema using mongoose, perform the following changes to your file of model

const mongoose = require('mongoose');

const childSchema = mongoose.Schema({
    heartRate: {type: Array, required: true}
    array: {type: Array, required: false}, //change the required parameter based on your requirement
});


const parentSchema = mongoose.Schema({
    dailyReadings: {
        type: childSchema,
        required: false //change the required parameter based on your requirement
    },

});


module.exports = mongoose.model('modelCollection', parentSchema);

So basically you need to define the child schema, and change the type of dailyReadings to that schema and add to the array of different objects.

Upvotes: 1

Related Questions