Insert js variables in projection?

Hello

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)=>{
 console.log(r[0].data.sensors.sensor)
});
1 Like

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
data.sensors.0.${sensorName}

Find !!! We must use an array and backtiks :wink: why???
[data.sensors.0.${sensorName}.data]

Try simply:

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

I indeed did forget the square brackets.

3 Likes

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

1 Like

Thank You so much, I am an beginer and i was stuck at this for almost 4 hrs and now i get solution