Mongosh error while practicing chapter 4, quiz 2

If i run the following query on the sample_training database I get a correct response:

query: sample_training> db.inspections.find( { $or: [{ date: 'Feb 20 2015' }, { date: 'Feb 21 2015' }] }, { $not: { sector: 'Cigarette Retail Dealer - 127' } }).count()


result: 380

but if I run the exact same query but eliminating the count() I get the following error:

sample_training> db.inspections.find( { $or: [{ date: 'Feb 20 2015' }, { date: 'Feb 21 2015' }] }, { $not: { sector: 'Cigarette Retail Dealer - 127' } })


MongoServerError: FieldPath field names may not start with '$'. Consider using $getField or $setField.

It would seem logical that if the query is wrong, the count() will also throw and error. why one succeeds and the other not?

The $not part is not really part of the query. It is taken as the second argument to the find() function.

The closing brace after the closing square bracket terminates the first argument. I have no clue as to why it does not complain in the count() case but the second argument seems to be ignored in this case.

The real query for the intent of your query should be something like:

{ $or: [{ date: 'Feb 20 2015' }, { date: 'Feb 21 2015' }] , sector: { "$ne" : 'Cigarette Retail Dealer - 127' } }

Hi Steeve.

Thanks for the reply, I realize that there must be an error with the query, tho I didnt know the exact reason so thanks for pointing out that $not in this case was not part of the query and was taking as the second argument to find().

my other concern is that it seems logical that both queries (with and without count()) should fail, can this be a bug?

1 Like

I would guess it is an optimization rather than a bug. The second argument is a projection which is not need when just counting. It is probably completely ignored.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.