Yigit Can
Yigit Can

Reputation: 361

Getting array insted of [object OBJECT] type in mongodb

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?

Upvotes: 1

Views: 1341

Answers (2)

James Bubb
James Bubb

Reputation: 3173

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).

Upvotes: 1

Den Kison
Den Kison

Reputation: 1084

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

Upvotes: 0

Related Questions