skip to Main Content

I am trying to retrieve data in my MongoDB database. If I have the following below in my mongoDB database, I want to select the Password given the Username. So in this case, I will be looking through the database for a Username that is ‘e’ and retrieving the password associated with that specific Username. I’ve tried looking everywhere but I can’t seem to find a solution on how to do it. I am using express, node, and mongoDB for this personal project. What I have so far is just looking up with database with .find({ Username: Username} and it outputs the entire JSON object.

To clarify, I will be sending a request with a Username of value ‘e’ and looking it up the database trying to retrieve the value of Password.

{
    _id: 62d7712e6d6732706b46094e,
    Username: 'e',
    Password: 'hi',
    __v: 0
  }

2

Answers


  1. find takes multiple inputs you can give the select statements also in find itself

    so the query will be like

    db.collectionName.find({username:'e'},{_id:0,password:1})

    mongo by default fetch _id all the time by default so you need to specifically mention to not fetch _id thus _id :0

    Login or Signup to reply.
  2. for such scenarios, there are 2 options if username is unique i would suggest to go with findOne rather then find

    db.collectionName.findOne({username:'e'}).password

    the same will work if you have multiple records with same username but you want only the first record

    but if you want data of all the records as array

    db.collectionName.find({username:'e'},{_id:0,password:1})..map( function(u) { return u.password; } )

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search