Hi Team
I have some test documents:
{"_id":{"$oid":“5f328c3a03792828c45940dd”},“Children_Num”:8,“Children”:[{“name”:“Snir”,“dob”:“1995-09-01”,“dep”:false},{“name”:“Iron”,“dob”:“1999-03-19”,“dep”:false},{“name”:“Sivan”,“dob”:“2003-05-31”,“dep”:true}]}
On Compass I run succesfuly this code:
db.Children.update([{$match: {
Children_Num: {
$gte: 0
}
}}, {$set: {
Children_Num:{$size:"$Children"}
}}])
I would like to update Children_Num field accordingly using updates.
I tested this code successfully:
db.Children.update(
{ _id: ObjectId(“5f328c3a03792828c45940dd”)},
{$set:{Children_Num:8}})
But When I tried to replace the 8 with {$size:"Children"}
I got an error
The dollar () prefixed field ‘$size’ in ‘Children_Num.$size’ is not valid for storage
Please advise
Thanks
Tal
Hi @Tal_Shainfeld,
The initial command works since it is an expressive update using an aggregation pipeline whitin the update.
This is exactly why this was introduced in 4.2 to allow you to compute those expressions whithin the same update.
You cannot use a $size or $expr in a “clasic” $set clause.
Why can’t you use the Pipiline method:
db.Children.update([{$match: {
_id: ObjectId("5f328c3a03792828c45940dd")
}}, {$set: {
Children_Num:{$size:"$Children"}
}}])
Best regards,
Pavel
Hi Pavel
I’m running MongoDB server version: 4.4.0.
Yet when running the code you sent
(I got error on the bracers
db.Children.update({$match: {_id: ObjectId(“5f328c3a03792828c45940dd”)}},
{$set: {Children_Num:{$size:"$Children"}}})
I got this:
errmsg’ : ‘unknown top level operator: $match’"
But
I tried this on compass successfully:
[{ $match: { Children_Num: { $gte: 0 } }}, { $set: { Children_Num: { $size: “$Children” } }}]
And on the mongo shell it failed:
Same it failed on NoSQLBooster:
Thus I guess the update makes the differences
So I tried on the mongoshell both:
Got error on update when aggregte is fine .
Please advise
Thanks Tal
Hi @Tal_Shainfeld,
In compass you missed []
so the engine will understand its a pipeline.
In the shell it might be some hidden character or the quotes are bad ones. What version of shell is this?
Best
Pavel
Hi Pavel
I tried 2 codes: the example you send me with $Sum that works, and my with $size was not run. I run it on same mongo server and shell .
I copied from the compass to shell thus no typo errors.
Please try my code and see if works for you:
db.Children.update([{$match: {
Children_Num: {
$gte: 0
}
}}, {$set: {
Children_Num:{$size:"$Children"}
}}])
Document
{"_id":{"$oid":“5f328c3a03792828c45940dd”},“Children_Num”:8,“Children”:[{“name”:“Snir”,“dob”:“1995-09-01”,“dep”:false},{“name”:“Iron”,“dob”:“1999-03-19”,“dep”:false},{“name”:“Sivan”,“dob”:“2003-05-31”,“dep”:true}]}
Mongoshell beta 0.1. 0 and directly on mongodb and also on NOSQLbooster.
Mongo ver 4.4 and 4.2 also
Thanks a lot
Tal