SJaka
SJaka

Reputation: 840

How to insert a field in an existing document in MongoSH

I've to insert a new field with a boolean value in some documents in the students collection with the following structure:

{
  _id: ObjectId("61c9cffcf9b7043141272c5b"),
  createdAt: 2021-12-27T14:38:52.025Z,
  updatedAt: 2022-07-26T10:12:56.887Z,
  deletedAt: null,
  fullName: 'Karina Kuznetsova',
  address: 'Chicago IL',
  Major:'Computer Science',
  __v: 0,
}

I'm running the following query in MongoSH locally in Mongo Compass:

db.students.aggregate([
    {
        $match: { 
            "_id": ObjectId('61c9cffcf9b7043141272c5b')
        }
    },
    {
        $set: { "transferred": true }
    }   
]);

I'm expecting the field to be added to the document like this:

{
  _id: ObjectId("61c9cffcf9b7043141272c5b"),
  createdAt: 2021-12-27T14:38:52.025Z,
  updatedAt: 2022-07-26T10:12:56.887Z,
  deletedAt: null,
  fullName: 'Karina Kuznetsova',
  address: 'Chicago IL',
  Major:'Computer Science',
  __v: 0,
  transferred: true
}

However, the original document remains the same, without the transferred field.

Option 2

I've also tried this way:

const studentsList = db.students.find({
    "_id": ObjectId('61c9cffcf9b7043141272c5b')
});

studentsList.forEach(student => {
    const result = db.students.updateOne(
        { _id: student._id },
        {
            $set: { "transferred": true }
        });
});

What am I doing wrong?

Upvotes: 1

Views: 87

Answers (1)

Yong Shun
Yong Shun

Reputation: 51450

Use the update function instead to update the document.

The aggregate function is used to return the queried document, but will not update the existing document in the collection.

db.students.update(
    {
        _id: ObjectId('61c9cffcf9b7043141272c5b')
    },
    {
        $set: { "transferred":true }
    });

Upvotes: 1

Related Questions