0

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

1
  • 1
    use .map on the array and retrieve the id, endless examples on that online... Commented Dec 18, 2020 at 17:31

2 Answers 2

1

You can do the following,

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

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

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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.