-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Updating an embedsMany child directly #2618
-
Hi,
I've got a database of products and each product has multiple variants. A variant is also a Product model. There are about 2000 products, and 3000 variants.
Periodically, I'm having to loop through the data and update stock values. We get a stock spreadsheet with SKU and corresponding stock values.
To get the relevant model, I'm performing the below:
$model = $this->provider->products() ->where('sku', $sku) ->orWhere('variants.sku', $sku) ->select(['_id', 'sku', 'variants._id', 'variants.sku']) ->first(); $model->variants->firstWhere('sku', $sku)?->setStock($stock) ?? $model->setStock($stock);
The problem is, ideally I'd like my query to return the child itself, but in all cases it'd still return the parent and then I'd have to drill down into the variants making the process very inefficient. Is there any way I am able to make this more efficient by querying the variants directly?
Chris.
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 1 reply
-
Do you need to retrieve the model data or can you update the database directly?
This can be done with 2 queries
// Update the document where sku matches in the root document YourModel::where('sku', $skuToUpdate) ->update(['stock' => $newStockValue]); // Update the document within the "variants" array YourModel::where('variants.sku', $skuToUpdate) ->update(['variants.$.stock' => $newStockValue]);
But I think it's possible to combine them using the $set
aggregation pipeline with $cond
.
Beta Was this translation helpful? Give feedback.
All reactions
-
I was only pulling the record so I could compare the SKU. Great, I didn't know you could do variants.$.stock
, I'll give that a go - thank you! And I presume $ will only update the variant that matches that SKU?
But I think it's possible to combine them using the $set aggregation pipeline with $cond.
Being my first time using MongoDB, this one goes a little over my head but I'll take a look!
Beta Was this translation helpful? Give feedback.