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()

and:

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

then, manually calculate.

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

db.trips.aggregate({$subtract:[db.trips.find({"pop":1988}).count(),db.trips.find({"pop":{$gt:1988}}).count()]})

Hello!

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.

1 Like

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.