Select a data range What did I miss?

Hello :wink: it’s my first message here ! thanks for your help.
i am a newbie on mongo and i am unable to output a range of values on a find.
I am using the latest nodejs driver.

// node route

router.get('/sel', (req, res)=>{
async function selecDatas() {

    const client = new MongoClient(uri, { useUnifiedTopology: true } )

        try {

            await client.connect( );

            const database = client.db('training');

            const collection = database.collection('emoncms');

          

            collection.find({ _id : ObjectID('5fc38b2f2626be03a023df57')}, 
{ 'exams.notes' :  { $lt : 3 }} ).toArray(function(err, docs) {

                console.log("Found the following records");

                console.log(docs[0].exams);
            });
        } catch(e) {
            console.log(e)
        }
};

    selectDatas().catch(console.dir);
    res.end()
});
// return all exams ... not only $lt3 ???
  name: 'Json',
  surname: 'Bourne',
  exams: [
    { _id: [ObjectID], notes: 1 },
    { _id: [ObjectID], notes: 2 },
    { _id: [ObjectID], notes: 4 },
    { _id: [ObjectID], notes: 3 }
  ]
}

Hello @Upsylon_Developpemen, welcome to the MongoDB community forum.

You can use the $filter array operator to select a range of data from an array.

1 Like

A big thank-you ! I’ve been looking for a solution for days.
I was in hell! : - / I needed this for a job. I’m going to read more about the documentation that I thought I had already read in depth. Thanks again, you’re saving my day :wink:

The solution:

collection.aggregate([
    { $project: {
        exams: {
            $filter: {
                input: "$exams", // le tableau à limiter 
                as: "index", // un alias
                cond: { $lt: [ "$$index.notes", 2 ] }
            }
        }
    }}
])
.project({'exams.notes' : 1})
.toArray(function (err, doc) { console.log(doc[0].exams)});
1 Like

One last thing: how do you target a specific document?
I tried different things but mongo always makes either the first doc or undefined: - /
// ! dont work !
collection.aggregate( { _id : ‘5fc38b2f2626be03a023df57’ },[

            { $project: {

                    exams: {

find sorry! :slight_smile:
collection.aggregate([{ $match : query },…

1 Like

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