-2

I am using a query with a projection to retrieve only specific fields from a MongoDB collection. Is it required to output the results of such a query to an Array? I wasn't able to find any working example without this conversion to an array.

 db.collection("collection").find({}, { projection: { Name : 1, Price : 1 } }).toArray( (err, result) => {
   if (result) {
     console.log(result)
   }
 })

However, by outputting the results to an Array, I am obtaining the result in the following format (a JSON formatted output within an array of 1):

[ {key1:value1, key2:value1}, {key1:value2, key2:value2}, ...]

I would like the results to be outputted as JSON.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
JF0001
  • 819
  • 7
  • 30
  • Isn't `const result = db.collection("collection").find({}, { projection: { Name : 1, Price : 1 } })` the format u look for? – Minsky Nov 06 '20 at 00:28

1 Answers1

0

You can loop through each element in the array and print them individually. One way to do that is using forEach. It would look like this:

db.collection("collection").find({}, { projection: { Name : 1, Price : 1 } }).toArray( (err, result) => {
   if (result) {
     result.forEach(doc => console.log(doc))
   }
 })
Montgomery Watts
  • 3,806
  • 2
  • 10
  • 24
  • but he needs more than 1 document – Minsky Nov 06 '20 at 00:22
  • Maybe I misunderstood due to this part: `a JSON formatted output within an array of 1`. @Minsky Are you trying to print each document without the square brackets? @JF0001 – Montgomery Watts Nov 06 '20 at 00:25
  • it's not very precise tbh :-) – Minsky Nov 06 '20 at 00:31
  • Yes indeed, I would like the results to be outputted without the square brackets. And yes, I need more than one document, and thus findOne cannot be used, – JF0001 Nov 06 '20 at 01:34
  • Thank you Montgomery Watts. However, I would like to send the result to the front-end, and not used it on the back-end, explaining why I would like the results to be in JSON format, without the square brackets. I have difficulty believing that this could be done with the findOne function, but not with the find() function. – JF0001 Nov 06 '20 at 01:44
  • https://stackoverflow.com/questions/19696240/proper-way-to-return-json-using-node-or-express @JF0001 – Montgomery Watts Nov 06 '20 at 01:46
  • Thank you again. But even if I use JSON.stringify, I am still having the square brackets when transferred to the front-end. Isn't there a query I can make, which does not return the results into an Array? I could do some manipulations on the result, but I find it hard to believe that their shouldn't be a way to do this without going through such manipulations. – JF0001 Nov 06 '20 at 01:52