A
A
Anton2021-01-26 20:10:28
MongoDB
Anton, 2021-01-26 20:10:28

What is the correct way to do Foreach in mongodb?

Hello.
For each element of the input array (str), you need to do a find with a check: if > 1 document, print the name of these documents and go to the next one, if = 1, then execute insert in name and subname (just change 2 fields), if 0 print name and to the next one.
Example:

var list = [001, 002, 003];     //исходный список номеров документов для исправления
   for list_id in list:     //для каждого элемента списка запускаем поиск
      var counter = db.collection.find ({"name": "abc", "Number":  {$in: [list]}}); //в переменную counter вносим кол-во найденных документов для последующего сравнения
         if counter is not $gt 1 and $ne 0 then //условие - больше 1 и не равно 0
            db.collection.update ({list_id}, {$set: {"name": "cba", "subname": "etc"}})  //изменяем в текущем документе с list_id два поля name и surname
         else print ({list_id}); //если документов 0 или больше 1, выводим их номера

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