Hi @KamelA,
Let’s say I have these 2 docs in my collections:
[
{
_id: ObjectId("6214d7d015bfcf433d5b7d33"),
name: 'factory',
num: 3,
workers: [ 'a', 'b', 'c' ],
testers: [ 'a', 'b' ],
developers: [ 'c' ],
status: 'NOT_FULL'
},
{
_id: ObjectId("6214d7ed15bfcf433d5b7d34"),
name: 'factory',
num: 3,
workers: [ 'a', 'b', 'c' ],
testers: [ 'a' ],
developers: [ 'c' ],
status: 'NOT_FULL'
}
]
The first one needs a status update.
We can do it like this:
db.coll.updateMany({
status: {$ne: "FULL"},
$expr: { $eq: [
{$size: "$workers"},
{$add: [{$size: "$testers"}, {$size: "$developers"}]}
]}
},
{$set: {status: "FULL"}})
Which would work better if the status field was indexed.
This query would also be faster if the array sizes were stored (and indexed) instead of being re-calculated all the time.
It’s usually fairly easy to maintain the size of the array and the array in sync by using in the same update operation $push or $pop for the array and $inc for the size.
Cheers,
Maxime.