Ticket:Projection Why use project() over projection, they both seem to work?

In the Ticket: Projection lesson in Chapter one, I used projection, as shown in the lesson video, to pass the tests and complete the lesson. Like this:

cursor = await movies.find({ “query” }, { projection: { title: 1 } })

Then I discovered in the ‘detailed answer’ that I could also have used MongoDB Driver project() method like this:

cursor = await movies.find({“query” }).project({ title: 1 })

Why is project() recommended over projection when including a projection document with find()? They appear to return the same results.

The MongoDB docs don’t shed much light on why you would use one over the other:
https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/

I would like to get a better understanding about this. If you know the answer or can point me to some documentation please let me know. Thanks.

Hey @wagner.don

From my understanding in the context of the Nodejs mongodb driver they are both the same. However the .project() is not something that can be used in the mongo shell or some of the other drivers.
For example
PHP:

$cursor = $db->inventory->find(
    ['status' => 'A'],
    ['projection' => ['item' => 1, 'status' => 1]]
);

Go:

projection := bson.D{
	{"item", 1},
	{"status", 1},
}

cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"status", "A"},
	},
	options.Find().SetProjection(projection),
)
2 Likes

@natac13

Thank you for your response. I agree with what you said. I’ll assume then that it is okay to use either format in a nodejs environment.

1 Like