Chapter 4: Advanced CRUD Operations Lab 2: Comparison Operators. $subtract

Hello there, for this question:

What is the difference between the number of people born in 1998 and the number of people born after 1998 in the sample_training.trips collection?

The simplest way is to do this way:

db.trips.find({"birth year":1988}).count()


db.trips.find({"birth year":{$gt:1988}}).count()

then, manually calculate.

There’s a sophisticated method to do something like the code bellow?



It depends on what exactly you want to do.

What about a function like this?

function substraction(fromThis, substract){ 
const a = db.trips.find({"birth year":substract}).count(); 
const b =  db.trips.find({"birth year":{$gt:fromThis}}).count(); 
return b - a

Or shorter

function substraction2(fromThis, substract){ 
const a = db.trips.count({"birth year":substract}); 
const b =  db.trips.count({"birth year":{$gt:fromThis}}); 
return b - a

It will save you some typing.


nice! I didn’t know I can store in variables in mongoDB. still much to learn in this road… …luckly it’s a chill trip.
thanks friend!


You’re welcome :slight_smile:

Feel free to ask any other questions.

I am executing this command in powershell:

function substraction(FromThis, substract) { const a = db.trips.count({ “birth year”: 1998 }); const b = db.trips.count({ “birth year”: { “$gt”: 1998 } }); return b - a}

The result is:
[Function: substraction]

Hi @Paramjit_Singh, you have to call the function separately after declaring it.
Please execute the following after the declaration:

substraction(FromThisValue, substractValue)

And hopefully, your function will get executed.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

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