whathetech Database,Mongodb,node.js MongoDB – Projection

MongoDB – Projection

Projection means asking the DB to get only the values that we are interested in. For example, if the document has 10 fields and we only want to get 1 field, then we can specify that field
In our youtubeSchema we have 11 fields. Let us just get ID and Title for all the videos. Let us first do this using mongo client

> db.youtubes.find({}, {_id: 1, title: 1}).pretty()
{ "_id" : "EUoe7cf0HYw", "title" : "Taylor Swift - Gorgeous (Lyric Video)" }
{
        "_id" : "4LfJnj66HVQ",
        "title" : "Lil Pump - \"Gucci Gang\" (Official Music Video)"
}
{
        "_id" : "CwfoyVa980U",
        "title" : "Charlie Puth - \"How Long\" [Official Video]"
}
{
        "_id" : "5Zs_5VghD6U",
        "title" : "Brett Eldredge - The Long Way (Official Music Video)"
}
{ "_id" : "ZiPwPqXeJUw", "title" : "Young Dolph - Believe Me" }
{
        "_id" : "M020Ajhkojg",
        "title" : "Chris Brown - High End (Official Video) ft. Future, Young Thug"
}
{
        "_id" : "Tx1sqYc3qas",
        "title" : "Marshmello - Silence Ft. Khalid (Official Music Video)"
}
{
        "_id" : "HiH3VlkV6zk",
        "title" : "Gucci Mane - Members Only [Official Music Video]"
}
>

Now, lets do the same using Node.JS
We will create a end point for this so that we can examine the result in our browser

 //server.js
        app.get('/getTitle', function (req, res) {
            console.log('get title');
            dao.getTitle().then(response=>{
                //console.log(response)
                res.status(200).send(response);
            })
            .catch(err=>{
                console.log(err);
                res.status(400).send('Failed to fetch');
            });
        });

Now update the DAO

 //dao.js
    getTitle: function () {
        return new Promise(function(resolve, reject) {
            let query1 = {};
            let query2 = {title: 1}
            Youtube.find(query1, query2, function (err, response) {
                if (err) {
                    return reject(err);
                }
                return resolve(response);
            });
        });
    }

Now, start the server and call the api though the browser

http://localhost:3000/getTitle

You can see that the server return only two fields, id and title. You might notice that you are getting _id even thought you did not specify it in the projection. This is because the DB by default returns _id for all queries.
If you do not want the id, you can simply remove it from the projection by doing this

 //dao.js
    getTitle: function () {
        return new Promise(function(resolve, reject) {
            let query1 = {};
            let query2 = {_id: 0, title: 1}
            Youtube.find(query1, query2, function (err, response) {
                if (err) {
                    return reject(err);
                }
                return resolve(response);
            });
        });
    }

Tags: , , , , ,