skip to Main Content

I need to add a missing counter field in my documents using the mongoshell (v4).

In JS I would do something like this:

const affected = await Data.findMany({ dataId: { $exists: false }}).toArray()
affected.map((d, i) => {
    Data.updateOne({ _id: d._id }, { $set: { dataId: i + 1 }})
})

Is it possible to do this directly in the shell?

2

Answers


  1. It’s almost identical.

    Mongo shell provides the capability to use JavaScript code directly in the shell.

    use your_database
    
    const affected = db.data.find({ dataId: { $exists: false }}).toArray()
    affected.map((d, i) => { db.data.updateOne({ _id: d._id }, { $set: { dataId: i + 1 }}) })
    
    Login or Signup to reply.
  2. This can also be done using a single query:

    db.collection.aggregate([
      {$match: {dataId: {$exists: false}}},
      {$setWindowFields: {
          sortBy: {_id: 1},
          output: {dataId: {
              $sum: 1,
              window: {documents: ["unbounded", "current"]}
          }}
      }},
      {$merge: {into: "collection"}}
    ])
    

    See how it works on the playground example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search