findOneAndUpdate

How can I findOneAndUpdate with an expression of
{$expr: { $lt: [{ $size: “$users” }, “package.maxUserCount”] }}

I want to update a document where users array size is less than maxUserCount.

It does not work, somehow it returns true on any document

{$expr: { $lt: [{ $size: “$users” }, “$package.maxUserCount”] }}

Hello Lasse, assuming your maxUserCount is 20, you could do something like this:

db.<<<yourCollection>>>.findOneAndUpdate({'users.20': {$exists: false}}, {'$set' : {<<yourProperty>>: <<newValue>>}});
1 Like

I had this post in my bookmark but was clueless until

and

I think that this is the difficulty about this one.

The maxUserCount cannot be assumed since it is the value of another field of the source document.

But

is the key and leads me to a variation where 20 is not assumed but taken from another field.

Congratulations for your new position at MongoDB.

1 Like

That works beautifully :+1:

1 Like

But but. I returned to the original post and original query. And it also works wonderfully. Yes the following

So I felt in the same trap I felt before, that is, assuming that there was a real problem other than typos in field names and/or missing $ in some field names. In the first post, package.maxUserCount was missing the $ but that was corrected promptly. I should also have requested sample documents. Perhaps the discrepancy is between the field name

or the text requirement

I tried different typos variations and the one that

is the one where the $ sign is missing in front of package.maxUserCount. When the dollar sign is present with a non existing field name the query is false for all documents.

2 Likes

@Lasse_Johansen, it has been 5 days since you have received valuable replies to your original post.

We and all readers would appreciate a followup. Perhaps even closure by marking one of the post as the solution in case your issue was addressed correctly. And I think it was.

Thanks in advance

1 Like

Sorry for the late reply.

My 2nd post was actually the answer to my question. Adding the dollar sign made the query work.

Do I need to mark any of the answers as the correct answer, or how do one proceed to finish up a question?

You could certainly mark your second post as the answer but it lacks some information.

The missing $ as the possible cause was mentioned in the post

You decide which posts is more useful to the community and mark it as the solution.

1 Like