1

I have a mongodb collection with thousands of documents. I have different steps in this collection and their steps status is completed. I want to update particular steps status from Completed to Open. For example, I want to update status to "Open"only for steps three and four and the document overAllStatus to Started. I want to do this where "executionId" is "20200622104036256".

My documents/json structure. Collection name order_status

   {
  "_id" : ObjectId("5ef03d8f5f5775000921e5b9"),
  "executionId" : "20200622104036256",
  "stateNumber" : "123456",
  "overAllStatus" : "Completed",
  "steps" : [{
      "name" : "Step One",
      "status" : "Completed"
    }, {
     "name" : "Step Two",
      "status" : "Completed"
    }, {
     "name" : "Step Three",
       "status" : "Completed"
    }, {
     "name" : "Step Four",
       "status" : "Completed"
    }],
  "ABC" : {
    "status" : "Completed"
  }
  
}

After i execute the shell update script/query. All the documents where the "executionId" is "20200622104036256" will be looking as below

{
  "_id" : ObjectId("5ef03d8f5f5775000921e5b9"),
  "executionId" : "20200622104036256",
  "stateNumber" : "123456",
  "overAllStatus" : "Started",
  "steps" : [{
      "name" : "Step One",
      "status" : "Completed"
    }, {
     "name" : "Step Two",
      "status" : "Completed"
    }, {
     "name" : "Step Three",
       "status" : "Open"
    }, {
     "name" : "Step Four",
       "status" : "Open"
    }],
  "ABC" : {
    "status" : "Completed"
  }
  
}

1 Answer 1

1

Query :

/** Using updateMany to update multiple documents matching certain criteria */
db.order_status.updateMany(
  { executionId: "20200622104036256" }, // Filtering for specific docs
  { $set: { overAllStatus: "Started", "steps.$[element].status": "Open" } }, // Update specific element in an array
  { arrayFilters: [{ "element.name": { $in: ["Step Three", "Step Four"] } }] } // Returns specific elements in `steps` array that matches criteria for update
);

Ref : arrayfilters-for-an-array-update-operations

Note :

If you wanted to update overAllStatus field only in case where, for documents with executionId: "20200622104036256" and have at-least one step element with name either "Step Three" or "Step Four" - then your filter part of .updateMany() should be :

{"executionId" : "20200622104036256", 'steps.name': { $in : ["Step Three","Step Four"]}}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.