1

I am new to MongoDB, my native language is Spanish. So I'm not sure how to find what I need.

I will try to make myself understandable.

I do this query and the result is an array.

For example :

Users.find({passport:123, (err, result) => {
   //output of result
   [ 
     {"nombre":"pedro","apellido":"jose"},
     {"nombre":"pablo","apellido":"jacinto"},
     {"nombre":"jose","apellido":"berta"},
   ]

I want to know if there is a more effective way to do something so that using some function from mongodb I can customize the output to avoid doing something like this:

Required Output :

   [ 
     {"name":"pedro","lastname":"jose"},
     {"name":"pablo","lastname":"jacinto"},
     {"name":"jose","lastname":"berta"},
   ]

is there any way to process the output information directly from mongoDB?

2
  • So do you wanted to nombre convert to name & apellido to lastname ? If yes there is no such thing that does directly, but you can write query to map nombre to name.. Commented Mar 24, 2020 at 3:48
  • result.map((element)=>{ return {name:element.nombre,lastname:element.apellido} } ? Commented Mar 24, 2020 at 3:50

1 Answer 1

2

You need to use MongoDB's Aggregation to do that :

db.collection.aggregate([
  /** Filter docs based on criteria */
  {
    $match: {
      passport: 123
    }
  },
  /** Transform fields into required form */
  {
    $project: {
      name: "$nombre",
      lastname: "$apellido"
    }
  }
])

Test : MongoDB-Playground

Ref : $match , $project

Sign up to request clarification or add additional context in comments.

8 Comments

I am using mongoose, I am too new, in this .. how can I get the result? a callback does not work Transaccion.aggregate([{...}], (err, value) => {})
@yavg : callbacks should work, are you seeing any error ? Check this in case if you think callbacks don't work :: (stackoverflow.com/questions/23805772/…)
I am getting this error: i.imgur.com/UH13l1C.jpg , can you please tell me how to correct it. I do not understand and excuse my ignorance.
@yavg : As error says you should pass all stages in an array like :: .aggregate([{},{}]) but not like :: .aggregate({},{})
@yavg : It seems ok, is that throwing an issue ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.