Using multiple $project stages

Hi,

In the last section of the video - “Lecture: Shaping documents with $project” in Chapter 1 in “Things to Remember” slide, the 3rd bullet point says - $project can be used as many times as required within an Aggregation pipeline. I tried using multiple $project stages in Aggregation pipeline, there was no syntactical error but results with empty braces. Please refer output below and the attached snapshot if required.
Please guide.

MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.solarSystem.aggregate([{ “$project”: { “_id”: 0, “name”: 1 } },{ “$project”: { “_id”: 0, “gravity.value”: 1 }}]);
{ }
{ }
{ }
{ }
{ }
{ }
{ }
{ }
{ }

I tried removing the “_id”:0 field from 2nd $project stage, but got the same result.

Multiple%20projects%20stage%20-%20empty%20result

Thanks,
Sampreet

Hi,

That’s because you only included the name field in your first projection. Recall that the output of one stage is the input for the next stage, so after your first projection the documents passed to the next one only have the name key, therefore gravity.value is not available in the second projection. Please check this pipeline, which returns the gravity value on a new field called gravity:

db.solarSystem.aggregate([
    { "$project": { "_id": 0, "name": 1, "gravity.value": 1} },
    { "$project": { "gravity": "$gravity.value" }}
]);

José Carlos

Thanks Mr. Carlos.
Yes, missed on the pipeline point. It is clear now.

-Sampreet