21

I am going through a course on MongoDB. Below is my list of documents in a collection called 'flightData'. Below is result of find query:

flights> db.flightData.find()
[
  {
    _id: ObjectId("611aaa1c4a0269583c8d81b0"),
    aircraft: 'AirBus A308',
    departingFrom: 'Mumbai',
    arrivalStation: 'Moscow',
    departureDate: '24/09/2021',
    departureTime: '01:44',
    arrivingAt: '12:00',
    isOneWay: false,
    status: {
      description: 'on time',
      lastUpdated: 'One hour ago',
      details: { contact: 'John Doe' }
    }
  },
  {
    _id: ObjectId("611aaa554a0269583c8d81b1"),
    aircraft: 'AirBus A308',
    departingFrom: 'Kolkata',
    arrivalStation: 'Stockholm',
    departureDate: '24/09/2021',
    departureTime: '01:44',
    arrivingAt: '12:00',
    isOneWay: false,
    status: {
      description: 'on time',
      lastUpdated: 'One hour ago',
      details: { contact: 'Cool User' }
    }
  }
]

When they show the difference between update and updateMany through an example similar to below one:

flights> db.flightData.update({_id:ObjectId("611aaa554a0269583c8d81b1")},{"delayed":false})

In the lecture it works. However, in my case it throws below error:

MongoInvalidArgumentError: Update document requires atomic operators

Can someone please explain this behavior? Is it not supported for my version or something else?

I am using MongoDB 5.0.2, mongosh 1.0.5

YakovL
  • 7,557
  • 12
  • 62
  • 102
Chandan Kumar
  • 303
  • 1
  • 3
  • 11

2 Answers2

32

If you want to add the "delayed" field to the document you will want to use the $set operator

db.flightData.update({_id:ObjectId("611aaa554a0269583c8d81b1")},{$set:{"delayed":false}})

If you would like to replace the document you should use replaceOne

This command was added in mongodb 3.2 to avoid accidentality replacing the entire document when you mean to update a field

I.Blair
  • 481
  • 3
  • 7
  • 1
    you are suggesting an upsert command. The plain update command (without $set operator) in question is supposed to work as a replace command . – Chandan Kumar Aug 19 '21 at 08:41
  • yes, it should work without $set, however this $set worked for me. $set will work in every case if we have the field or not. if no field it will create that field and set the value – Ashish Saini May 24 '22 at 08:17
0

This may help someone so writing as answer.

In my case, I'm doing bulk write operation and missed a field that I'm trying to update in Mongoose Schema caused this issue. After correcting the Mongoose Schema, issue is resolved.

So, validate the fields that are used in update are configured in Schema if you are using Mongoose.

Ravi MCA
  • 2,491
  • 4
  • 20
  • 30