1

I am performing an aggregation query and I end up with the following Array that contains many objects.

enter image description here

How can I extract the field _id from each one of the afore-mentioned Objects?

Expected output would be an array of each of the _ids inside each object

4
  • Can you share the expected output? Commented Aug 1, 2021 at 15:18
  • Expected output would be an array of each of the "_id"s inside each object Commented Aug 1, 2021 at 15:20
  • Hi @azal can you share the actual data and query so that we can reproduce it Commented Aug 1, 2021 at 15:26
  • Using $project and $map: example. Is this example correct for you? Commented Aug 1, 2021 at 15:27

1 Answer 1

4

To get an array of every _id into you object you can use a $map.

Map is similar as JS map, check this:

const array = [
  {"id": 1,"other": ""},
  {"id": 2,"other": ""},
  {"id": 3,"other": ""},
  {"id": 4,"other": ""},
  {"id": 5,"other": ""}]
console.log(array.map(m => m.id))

You can get this approach using mongo $map into a $project stage like this:

With this aggregation you are creating a field called array where using $map return array.id, so it creates an array of desired ids.

db.collection.aggregate([
  {
    "$project": {
      "_id": 0,
      "array": {
        "$map": {
          "input": "$array",
          "as": "a",
          "in": "$$a.id"
        }
      }
    }
  }
])

Example here

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

2 Comments

That was exactly what I was looking for! I was quite confident about the usage of the map function but did not know how to use it. Cheers
No problem! Also if the issue has been solved, mark answer as accepted is appreciated.

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.