Node.js is a popular runtime platform to create programs that run on it.
It lets us run JavaScript outside the browser.
In this article, we’ll look at how to start using Node.js to create programs.
We can specify the fields that we want to return for each entry/.
For example, we can wrote:
const { MongoClient } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);
async function run() {
try {
await client.connect();
const testCollection = await client.db("test").collection('test');
await testCollection.deleteMany({})
const result = await testCollection.insertMany([
{ "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1 },
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
{ "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
]);
console.log(result)
const projection = { name: 1 };
const cursor = testCollection.find().project(projection);
await cursor.forEach(console.dir);
} finally {
await client.close();
}
}
run().catch(console.dir);
We call the project
method with an object that has the keys that we want to include in the keys.
The value is 1 means we include the given property in the result.
The _id
field is returned automatically by default.
#technology #software-development #programming #javascript