Insert js variables in projection?


I need to insert a js variable in my projection. How to do ?

The following statement does not work.

Thanks for help :wink:

let sensor = sensorName 

// I use node Driver. 
collection.find({ _id : ObjectID(boatId)} , 
     $project  : { 'data.sensors.0.$$sensor' : 1}
 }).toArray((err , r)=>{

You do that like you do it for any normal JS string expression.

The expression

'data.sensors.0.' + sensor

should work.

Driver code (like the above js string concat) can be mixed with mongo code,but the driver code runs before sending the query to mongo.

sensor is a js variable not a mongo variable

Its helpful to use driver code to generate mongo queries many times,not just a string concat
like here.

1 Like

Unfortunaltly no :-/ whith interpolation no more

Find !!! We must use an array and backtiks :wink: why???

Try simply:

$project : { ["data.sensors.0." + sensorName] : 1 }

I indeed did forget the square brackets.


Thanks Steeve ! your solution is more simple effectivly ! :wink: