1

I I had in mongodb colleciton documents like:

Documents in collection (each has name property):

[{ name: 'Alex', .. }, { name: 'Jane', .. } ... ]

How can I query db to get the result simply mapping the name property:

['Ale', 'Jane', ...]

?

2
  • Not really that clear to me. Do you mean a "collection" or an array within the "documents" in your collection. It is also especially hard when you do not show us what doesn't actually work. Commented Mar 31, 2014 at 10:14
  • updated OP, I just don't know how to do this. Commented Mar 31, 2014 at 10:22

1 Answer 1

1

What you would want to use is query projections.

Queries in MongoDB return all fields in all matching documents by default. To limit the amount of data that MongoDB sends to applications, include a projection in the queries.

For your example, your query would look something like this:

db.people.find( {}, { "name": 1 } )

This will extract all documents but only return the name attribute (and _id) for each one. To remove the _id attribute as well, you would have to explicitly specify that you don't want it:

db.people.find( {}, { "name": 1, "_id": 0 } )

In order to retrieve all of the names in one array, you could use a forEach function to assemble the data:

var names = [];
db.people.find( {}, { "name": 1, "_id": 0 } ).forEach( function( doc ){
  names.push( doc.name );
});
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks, but I know how to return name field, what I need is to get plain array as result, updated OP
And I wan't it do do without aditional javascirpt in callback
Sure thing, just wanted to give some more background info for future visitors.
May I ask why? This seems to be the simplest solution to retrieve all the data you requested...
@WHITECOLOR Lix seems to have asked you some clear questions, but did not tag you in the comments so you are not seeing them
|

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.