Home > OS >  Query to create a new field in all documents in MongoDb collection
Query to create a new field in all documents in MongoDb collection

Time:06-15

I am trying to add this new field to all documents in my collection using updateMany. I just cannot find the right way to do it. My field "sits" takes an array of objects. The object is no defined in the schema. However, it currently has 3 fields: sitNumber, isAvailable, isSuspended. I can insert documents with this structure just fine. I want to add the field price : 0 to all existing documents.

This is a sample document in the collection

{
flightName : 65ywdbs
sits: [
{sitNumber : 1, isAvailable: true isSuspended: false} //Want to add a price field here.
]
//etc etc
}

My SCHEMA looks like this:

//models/Flight.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const flightSchema = new Schema({

    flightName :{ type : String, required :true}, 
    sits : {type : Array,
         required : true}, 
    origin : {type: String, required : true},
    destination : {type : String, required: true},
    departure : {type : Date, required : true},
    arrival : {type : Date, required : true}
})

module.exports = mongoose.model('Flight', flightSchema)

This is the query that I have used to add the field price to each object in the array sits in each document of the colection:

//Controllers/dashboard.js

 addPrice : async(req, res) =>{
        try {
            const query =  await Flight.updateMany({}, {$set : {'sits.price':100}} )
            console.log(query)
        } catch (error) {
            console.log(error)
        }
      
        
    }


This makes sense to me but it is incorrect. Any help will be appreciated.

CodePudding user response:

You can do something like this using $[], the all positional operator.

Your problem is similar to the example to update all documents in an array:

The $[] positional operator facilitates updates to arrays that contain embedded documents. To access the fields in the embedded documents, use the dot notation with the $[] operator.

db.collection.updateOne(
  { <query selector> },
  { <update operator>: { "array.$[].field" : value } }
)

So in your case, your update will look like this:

const query = await Flight.updateMany({}, { $set : { 'sits.$[].price': 100 }})
  • Related