1

I have written a particular query which fetches the Firstname from the users array from a document , the query successfully runs and displays in the MongoPlayground website but when I try to run the code in JavaScript and try printing to the console it gives me NULL or no output

 let dataset= await collection.find({
            "users.0.firstName": "Terry"
          },
          {
            _id: 0,
            "firstName": {
              $map: {
                input: "$users",
                in: "$$this.firstName"
              }
            }
          }).toArray();
          
          if(dataset&dataset.firstName)
          {
            for(let i=0;i<50;i++)
            {
                console.log(dataset.firstName[i])
            }
          }

tried removing the Toarry() method , tried without the loop but still doesn't give me any result

MongoPlayground data

enter image description here

tidersky
  • 39
  • 9

1 Answers1

1

Try to change your code to:

let dataset = await collection
    .find(
        {
            'users.0.firstName': 'Terry',
        },
        {
            projection: {
                _id: 0,
                firstName: {
                    $map: {
                        input: '$users',
                        in: '$$this.firstName',
                    },
                },
            },
        }
    )
    .toArray();

if (dataset && dataset.length > 0) {
    const firstNames = dataset[0].firstName;
    for (const name of firstNames) {
        console.log(name);
    }
}
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29