1

I have a collection of documents stored in a MongoDB database that looks like this:

[
  {
    _id: 5fe72e02b237503088b8889b,
    code: '000001403',
    name: 'John',
    date: 2018-12-01T21:00:00.000Z,
    __v: 1
  },
  {
    _id: 5fe72e02b237503088b8889c,
    code: '000001404',
    name: 'Michael',
    date: 2018-12-01T21:00:00.000Z,
    __v: 1
  }
]

I need to remove the "code" field from all documents in the collection and keep the documents, that is, I need the following result:

[
  {
    _id: 5fe72e02b237503088b8889b,
    name: 'John',
    date: 2018-12-01T21:00:00.000Z,
    __v: 1
  },
  {
    _id: 5fe72e02b237503088b8889c,
    name: 'Michael',
    date: 2018-12-01T21:00:00.000Z,
    __v: 1
  }
]

I also removed the field from the model:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ItemSchema = new Schema({
  // code: String,
  name: String,
  date: {
    type: Date,
    default: Date.now
  },
});

module.exports = mongoose.model('Item', ItemSchema);

I don't know if it is possible to use aggregation and the $unset method in this case, or is there another method?

Thanks.

Kiten
  • 457
  • 1
  • 5
  • 19

1 Answers1

2

You can achieve the desired result like this:

first you have to add the 'code' field back to your Schema and then run the following code.

after that you can remove the code field from the Schema again.

const res = await Item.updateMany({}, {$unset: {"code": 1}});

res.n; // Number of documents matched
res.nModified; // Number of documents modified

or

Item.updateMany({}, {$unset: {"code": 1}}).then(res => {
  console.log(res.n); // Number of documents matched
  console.log(res.nModified); // // Number of documents modified
}).catch(err => console.log(err));
Abbas
  • 600
  • 1
  • 12