1

Is there any solution for this problem?

Assume I've db as;

{
  name: "Alex"
  id: 1
}
{
  name: "Felix"
  id: 2
}


db.collection.find({}, {name:1, id:0}).toArray()

returns as;

result
   object
     name: Alex
   object
     name: Felix

I've already limit the fields to get only name as an array. Is there any way to do this? Why this query returns in [object OBJECT] format?

My solution is; traversing result and insert each name object into some array. I'm looking something different than this. Maybe it's about the query I wrote?

2 Answers 2

1

Are you passing a function in to toArray() ?

var mongo = require('mongodb').MongoClient;
var mongoURL = 'mongodb://localhost:27017/example';

mongo.connect(mongoURL, function(err,db){
  db.collection('collection').find({}).toArray(function(err, res){
    console.log(res);
    db.close();
  });
});

Running the above with your data will return all the documents stored:

C:\Users\james.bubb\node\>node test.js
[ { _id: 571798647849a3c217e84d61, name: 'Alex', id: 1 },
  { _id: 571798757849a3c217e84d62, name: 'Felix', id: 2 } ]

Alternatively, to just display the names instead of logging the whole result to the console (or whatever you need to do):

res.forEach(function(doc){
  console.log(doc.name)
});

Where doc is each individual document you have stored.

Of course you can specify criteria to filter your results within the find() function.

There is a good introduction to using MongoDB with Node over on the NPM site (see here for details on selecting documents).

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

Comments

0

As i understand you need to get all names as an array, so in this situation you can use aggregation:

db.collection.aggregate([   
    {$group : {'_id' : "names", 'names' : {$push : '$name'}}}   
]);

As a result you will get this:

{ "_id" : "names", "names" : [ "Alex", "Felix" ] }

Then you can simply get all user names as array from query result

Comments

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.