0

I have a couple of inserts for a collection:

db.customerOrder.insert (
{
  "orders": [
    {
      "orderNumber": "ord003",
      "orderDate": ISODate("2020-01-10T00:00:00Z"),
      "staffNumber": "stf789",
    },
    {
      "orderNumber": "ord005",
      "orderDate": ISODate("2020-03-17T00:00:00Z"),
      "staffNumber": "stf444",
    },
    {
      "orderNumber": "ord005",
      "orderDate": ISODate("2020-02-22T00:00:00Z"),
      "staffNumber": "stf890",
    }
  ]
}
);

db.customerOrder.insert (
{
  "orders": [
    {
      "orderNumber": "ord001",
      "orderDate": ISODate("2020-04-23T00:00:00Z"),
      "staffNumber": "stf123",
    },
    {
      "orderNumber": "ord005",
      "orderDate": ISODate("2020-04-16T00:00:00Z"),
      "staffNumber": "stf444",
    }
  ]
}
);

db.customerOrder.insert (
{
  "orders": [
    {
      "orderNumber": "ord001",
      "orderDate": ISODate("2020-02-10T00:00:00Z"),
      "staffNumber": "stf123",
    },
    {
      "orderNumber": "ord005",
      "orderDate": ISODate("2020-04-10T00:00:00Z"),
      "staffNumber": "stf890",
    }
  ]
}
);

db.customerOrder.insert (
{
  "orders": [
    {
      "orderNumber": "ord005",
      "orderDate": ISODate("2020-05-15T00:00:00Z"),
      "staffNumber": "stf123",
    },
    {
      "orderNumber": "ord004",
      "orderDate": ISODate("2020-02-25T00:00:00Z"),
      "staffNumber": "stf890",
    }
  ]
}
);

These were inserted through a terminal, I am not using any server sided language like php and etc, just data manipulation using the terminal.

May I know how I can change the stfNumber to stf100 for all orderNumber with ord005?

I have tried this

db.customerOrder.update({"orders.orderNumber":"ord005"},{"$set":{"orders.$.staffNumber":"stf100"}})

Unfornately, only the first object with ord005 is updated with the staffNumber to stf100

1 Answer 1

1

You can use the filtered-Positional array update operator

your query may look something like this

db.customerOrder.updateMany(
    { "orders.orderNumber": "ord005" }, // filter part
    { "$set": { "orders.$[order].staffNumber": "stf100" } }, // update part
    { arrayFilters: [{ 'order.orderNumber': 'ord005' }] } // options part, to define which orders will be updated according to some condition
)

hope it helps

Sign up to request clarification or add additional context in comments.

2 Comments

it only updates all occurrences in the first document :(
okay, I have updated my answer, we need to use updateMany instead of update, I tested it in mongo shell, and it's working as expected, could you check it again?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.