How to return only the field value in mongodb

After applying the search operation in mongodb .. I get the following list of documents.

db.users.find(....) 

I got:

  { "text" : "Hey" } { "text" : "Hi" } { "text" : "Hello" } { "text" : "yes" } 

How can I convert it to

  ["Hey","Hi","Hello","yes"]. 

I tried

  db.users.find(...).map( function(u) { return "u.text"; } ) 

but he gives an error!

+6
source share
3 answers

Not sure what you are using in the language, but the basic concept:

 var result = [] db.users.find().forEach(function(u) { result.push(u.text) }) 

And the result value is returned:

 ["Hey","Hi","Hello","yes"] 
+8
source

At first, db.users.find(...).map() did not work, because db.users.find(...) does not return a real array to you.

So you need to convert to an array first.

 db.users.find(...).toArray() 

Then, if you use the map () function, it will work

  db.users.find(...).toArray().map( function(u) { return u.text ; } ) 

Another simple trick is to use .forEach ()

It will do the trick

 var cursor = db.users.find(...); // returns cursor object which is a pointer to result set var results = []; cursor.forEach( function(row) { results.push(row.text); }); results //results will contain the values 
+3
source

you can use

 var u=db.users.find({...},{text:1,_id:0}) while(u.hasNext()){print(u.Next().text);} 
+2
source

All Articles