Chapter 4: Lecture: Array Operators and Projection

Hi Guys , I noticed this.
db.listingsAndReviews.find({ “amenities”: “Wifi” }, { “price”: 1, “address”: 1, “_id”: 0, “maximum_nights”:0 }).pretty() this fails as expected but if you replace pretty() with count() it executes. Is the 0s and 1s in a projection limited to certain functions?

Hi @Alex_Kim,

First of all Welcome to the MongoDB Community forum, we wish you a happy learning.

Just to make sure that kindly don’t use an inverted comma within the query, in most of the cases it shows an error.

So now, this would be your query after using just " "
db.listingsAndReviews.find({ "amenities": "Wifi" }, { "price": 1, "address": 1, "_id": 0, "maximum_nights":0 }).pretty()

This query will return an error message,
Cannot do exclusion on-field maximum_nights in inclusion projection
which means that it cannot exclude maximum_nights in the inclusion projection i.e., you cannot have a mix of inclusion and exclusion projection (except for _id). You can read more here

So, if you use this following query,
db.listingsAndReviews.find({ "amenities": "Wifi" }, { "price": 1, "address": 1, "_id": 0, "maximum_nights":1 }).pretty()
where it’s completely inclusive projection (except _id) then it will works completely fine.

Note: Here projection is not limited to pretty() or count() functionality.
Moreover, you can refer to the documentation for more info.

If you still have any questions feel free to reach out to us.

Thanks,
Kushagra

1 Like

Hi @Kushagra_Kesav,

Thank you for the warm welcome to the community .
Thanks for pointing out the inverted commas and clarifying on the scope of projections.

I still don’t understand why the query when used with count() returns results. I expect it to fail, throw an error. The projection is not right.

Please check this out and clarify.
db.listingsAndReviews.find({ “amenities”: “Wifi” }, { “price”: 1, “address”: 1, “_id”: 0, “maximum_nights”:0 }).count()

Thank you for your time.

Regards,
Kim.

1 Like

Hi @Alex_Kim,

No, it wouldn’t fail, because here you are using count() functions, which is not going to project any documented output on the screen.

Whereas when you use the pretty() function it displays the documented output, so it becomes little precise that either query which is written, is following a fully inclusive or exclusive pattern.


If you still have any questions feel free to reach out to us.

Thanks,
Kushagra

2 Likes

Thank you Kushagra, that explains it. Now I get it.

Thank you for your time and prompt responses.

Happy to Join the MongoDB community.

Regards,
Kim.

2 Likes