Gustavo Rodrigues
Gustavo Rodrigues

Reputation: 61

Get array with all object specific values

I have the following code:

<db.collection>.find({ id : { $exists: true } })

this returns all documents with a id property. how can I make it return an array with all the values of that id? Example:

{_id: ---, id: 21162 }
{_id: ---, id: 23712 }

returns: [21162, 23712]

PS: I thought about using a repetition structure that would go through all the properties and push an array, but I think it’s unnecessary and I think it’s not the best way to do this

Upvotes: 0

Views: 31

Answers (2)

germanio
germanio

Reputation: 859

There are two options to achieve this:

The first one is to let Mongoose/MongoDB filter them, using the projection param:

// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();

this is an example from the docs, here: https://mongoosejs.com/docs/api.html#model_Model.find

The other option is what Sabbir suggested, but it requires the whole list of documents returned by Mongoose to be loaded into memory and be processed one element at a time.

Upvotes: 0

Md Sabbir Alam
Md Sabbir Alam

Reputation: 5054

You can do the following,

let data = [
{'_id': '---', 'id': '21162' },
{'_id': '---', 'id': '23712' }
];

let result = data.map(item => item.id);

console.log(result);

Upvotes: 1

Related Questions