0

I use MongoDB 6.0.

And I'm just trying to update each field with sequence number in mongosh. I want the field modified and update the collection.

The sequence_number will be given from random number.

Here's the example:

{
  _id: "1",
  name: "Ken"
},
{
  _id: "2",
  name: "Ryu"
}

And what I want to do is this:

{
  _id: "1",
  name: "Ken",
  sequence_number: "10"
},
{
  _id: "2",
  name: "Ryu",
  sequence_number: "11"
}

Does anyone help me?

Thanks.

I read the question.

How can I add a new field from another one value?

But the approach is a little different.

  • Hello, Where does value for `sequence_number` come from? also how do we know which `sequence_number` should be assigned to which document? It'll be better if you include some code that clarifies this. – Omkar76 Jun 15 '23 at 07:44
  • `sequence_number` is a random value. It could start 100, 500 or 10. But the each value should be different. – ThrowDevNull Jun 15 '23 at 07:49
  • And the document including `sequence_number` is write back to the same collection. – ThrowDevNull Jun 15 '23 at 07:50

1 Answers1

1

You can iterate over all documents in collection and call updateOne for each of them.

let sequenceCounter = 10;

db.users.find().forEach((user) => {
    db.users.updateOne(
        { _id: user._id },
        {
            $set: {
                sequence_number: sequenceCounter.toString()
            }
        });
    sequenceCounter++;
});

If collection contains large number of documents consider batching the operations with bulkWrite().

let sequenceCounter = 10;

const bulkOperations = db.users.find().toArray().map((user)=>{

     return {
        updateOne: {
          filter: { _id: user._id },
          update: { $set: { sequence_number: (sequenceCounter++).toString() } }
        }
      }
      
})

db.users.bulkWrite(bulkOperations);

If you are interested in generating the sequence_numbers during insertion of documents, consider reading https://www.mongodb.com/basics/mongodb-auto-increment. Mongodb does not have auto increment functionality built in. This approach uses a counter collection and js functions that are triggered when creating new documents.

Omkar76
  • 1,317
  • 1
  • 8
  • 22