S
S
Sergey Kornienko2021-11-27 14:56:48
MongoDB
Sergey Kornienko, 2021-11-27 14:56:48

How to add counter to MongoDB pipeline?

Faced with the task of updating the "order" field in many rows in mongoDB, everything seems to be simple, but I need to insert a number in the "order" field with an iterator step. But I didn’t find anywhere how to set a mutable variable in the pipeline in order to build a function based on it.

There is a set of fields like this:

[
   {"_id": "619ff3d26812666d818a5cd6", "sheet": 46, "order": 32, "name": "Row 1"},
   {"_id": "619ff3d26812666d818a5cd7", "sheet": 46, "order": 1, "name": "Row 2"},
   {"_id": "619ff3d26812666d818a5cd8", "sheet": 46, "order": 23, "name": "Row 3"},
]


I need to update all these fields, with match and sort
db.collection.update({"sheet": 46}, {
   $sort: {
      "name": 1
   },
   $set: {
      "order" : (вот тут мне нужно вставить итератор, который будет увеличиваться на +1 с каждой новой строкой)
   }
})

accumulator will not work here, because. it only works in a group, maybe you can pass it through $function, but how to store the value of the iterator somewhere in a variable, and increase it by +1 every line...

with js and forEach it's not a problem to do this, but I would like to use bson and pipeline for this operation.
if there are connoisseurs of mongoDB, tell me what can be done ...

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question