Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return only value of a field in mongodb

After applying the find 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 into

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

i tried

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

but it is giving error!

like image 325
shashank Avatar asked May 15 '14 10:05

shashank


People also ask

How do I return a specific value in MongoDB?

When you use methods such as find() or findOne() in MongoDB, by default you get the whole document returned. And if you use projections, you can return specific key/value pairs. But what if you only want the value? You can extract the value of a field by appending that field's name to your query when using findOne() .

How do I get a single value in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName.


2 Answers

Not sure what you language implementation is but the basic concept is:

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

And the returned value to result is:

["Hey","Hi","Hello","yes"]
like image 148
Neil Lunn Avatar answered Sep 28 '22 03:09

Neil Lunn


At first db.users.find(...).map() didn't work because db.users.find(...) doesn't return you a real array.

So you need to convert to array at first.

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

Then if you apply map() function will work

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

Another simple trick is using .forEach()

This 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
like image 21
mohamedrias Avatar answered Sep 28 '22 05:09

mohamedrias