Reputation: 91
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
Upvotes: 0
Views: 38
Reputation: 2184
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
Upvotes: 1