MongoDb Atlas projection

MongoDb Atlas projection

On the Atlas platform when I try to make a query that includes projections, example:
If I enter in the Find field of the movies collection this query:
{title: “Carmencita”}, {projection: {title: 1}}

It returns all the fields without applying the projection.

What am I doing wrong?
Thanks for answering

Note: I think it could be the new version of Atlas platform that does not support projections.

What do you mean by “Atlas Platform”? Atlas is simply a container that runs mongodb. I’m guessing you’re using the mongo client locally to connect and run queries?

The options object passed as the second parameter is specific to the nodeJS driver. One of the options you can pass is the projectoin object.

If you’re using mongo client (mongo shell) the way to do the same is to simply specify the fields:
For example:
db.movies.find({ name: ‘Back To The Future’}, {name: 1, _id:0}).

There’s no need to specify “Projection” because the second object passed to find in the mongo client should alwasy be the projection object.

Here you can find the documentation on the mongo shell commands:
https://docs.mongodb.com/manual/crud/

For the most part they will be similar to the mongoDB nodeJS driver but there will be differences between the two.

1 Like

@pawlowsg please see my response Cryptic failure messages, how to troubleshoot?

Hi nathan,

My understanding is that there is two ways to do projection in the mongoDB nodeJS driver.

  1. Pass the projection option in the find method as the second parameter.
  2. Call “project” method on the returned cursor from find (The way you are suggesting)

Documentation on all options that can be passed to find:
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#find

In both cases the way you do projection in the driver vs the shell is different. I was attempting to help linuxexp with his problem but I’m not sure where/how linuxexp is attempting to to do projection, he’ll have to provide more information.

While it is correct you can perform projection in two ways, the method of projecting that you may be used to in the shell is not the preferred way, and confusing the two lead to invalid syntax.

db.courses.find({course: "M220JS" }, {project: { students: 1 }}) is incorrect.

db.courses.find({course: "M220JS"}, { students: 1 }) is valid but not the preferred method with the Node driver.

courses.find({course: "M222JS"}).project({students: 1}) is the preferred way.

Generally if a builder pattern is exposed to us we should strive to use it. Not only is constructing the raw query less ergonomic and declarative, it’s far more error prone.