Search code examples
mongodbmongo-shell

How can I add each record to the sequence number in mongosh?


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.


Solution

  • 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.