1

I want an aggregation to transform an array of documents like this:

[
  {
    "key": "key1"
  },
  {
    "key": "key2"
  }
]

into an array of:

[
  "key1",
  "key2"
]

Thanks!

2

2 Answers 2

2

Issue with your query:

In your query when you're doing { $replaceRoot: { newRoot: "$key" } }, $key will get value of key field i.e; key1 for 1st doc & key2 for 2nd doc. But as $replaceRoot takes in an object and make that object as new doc (Root of the document) it's find a string value rather-than an object, which is why it's failing. Anyhow you need to use $group stage to do this which iterates on all docs (Vs) $replaceRoot stage will be executed on each doc individually.

Putting my comment as answer with added description : When you use aggregation you'll either get an empty array [] if not matching docs found/not docs exists Or else you'll get an arrays of objects/object [{},{}] or [{}] in the result. So you can't get an array of elements in the result like : ['key1','key2'], as I said aggregation result array will have a doc in it, then it will be like [{keys : ['key1','key2']}]. You can get it by using below query :

Query :

db.collection.aggregate([
  /** grouping all docs without any condition in `_id` & pushing all values to an array `keys` (name is just a choice), for unique values use `$addToSet` instead of `$push`. */
  {
    $group: { _id: "", keys: { $push: "$key" } } },
  {
    $project: { _id: 0, keys: 1 } // Optional stage, You need to remove `_id` from result as it's included by default
  }
])

Test : mongoplayground

Ref : aggregation-pipeline

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

Comments

1

You can do this by $group operator

db.getCollection('collection_name').aggregate([
  {
    $group: {
      _id: null,
      key: {
        $push: "$key"
      }
    }
  }
])

https://mongoplayground.net/p/NfLonicjkaZ

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.