Question

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!

Était-ce utile?

La solution

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"]

Autres conseils

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

Another option is simply to use distinct:

db.users.distinct("first_name");

Would return:

[
  "John",
  "Jennifer",
  ...
]

you can use

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

The correct answer here is the method .distinct() (docs)

In your case try it like this:

db.users.find(....).distinct('text')

That will return only the values.

best way is :

db.users.distinct("text");


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

You will get further information regargding this topic here : mongodb distinct

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top