Write a list of fields to an associated set of documents in the database

Hi, as the topic header says, I’m looking for a way to write an aggregation of fields back to a corresponding (equal number and order) set of documents in the database.
For example in the pymongo driver, and I have three documents with a ‘field’ parameter. Is there a single operation to carry out:
collection.update_many(
filter = {“documents”: “documents_key”},
values = {“$set”: {“value” : value1},
{“value” : value2},
{“value” : value3}}).

I don’t want to do it in a loop because it feels inefficient and ‘unclean’ and I’m sure this is a fairly basic question but Google being how it be nowadays I cannot for the life of me find out how to do this. Or if it is even possible

What do you mean by

Where is it used in

You have too many parenthesis in your $set. The syntax is

{ "$set" : {
    "field_one" , value_1 ,
    "field_two" , value_2 ,
    "field_three" , value_3
} }

To help you, we will need sample documents that we can cut-n-paste directly into our system. Expected resulting documents based on these sample documents are needed.

Hi Steeve,

Let’s say I have a collection in my database that contains however many records.
Now say I construct a filter that specifies 500 of those documents. And I need to set THE SAME FIELD in those 500 documents with a list of 500 values.

I am not setting DIFFERENT fields in the same document, but the same field in different documents.

I know I can use a loop but that doesn’t work with the filter unless I perform a bulk read first to gather the IDs, the ‘for’ loop also feels inefficient as the process jumps from executing business code to executing database code N times.

I only wrote ‘update_many’ as a placeholder for what I meant. Perhaps a poor choice as it overlapped with something that already exists.

For n documents, with n different values you need https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/.

To build the bulkWrite array you will need a loop to build something like:

bulk = [ 
  { "updateOne" : {
      "filter" : { /* filter for first document */ } ,
      "update" : { "field_name" : value_for_first_document }
  } } ,
  { "updateOne" : {
      "filter" : { /* filter for second document */ },
      "update" : { "field_name" : value_for_second_document }
  } } ,
  /* filter and value for other documents */
  { "updateOne" : {
      "filter" : { /* filter for last document */ },
      "update" : { "field_name" : value_for_last_document }
  } } 
]