0

I have this query in mongodb:

db.getCollection('users').aggregate([
    {
        $group: { 
            _id: "$type",
//             items: { $push: "$_id.type" }
//             items: { $addToSet: "$_id.type" }
        }
    },
    {
        $project: {  
            _id: 0,
            type: "$_id",
        }
    }
]).toArray()

This will return a list like this: [ {type: "AAA"}, {type: "BBB"}, {type: "CCC"} ]

But can I get something like this: ["AAA", "BBB", "CCC"]? Tried with $push and $addToSet but no result. Thank you for your time!

Later edit: You can find an example here: https://mongoplayground.net/p/-n0o5i6CnLq

3
  • 1
    you can group by null, like this _id: null instead of _id: "$type" Commented Dec 14, 2020 at 18:16
  • Can you please provide some sample documents? Commented Dec 14, 2020 at 18:17
  • @WernfriedDomscheit I added a link. And the result I want to obtain is ["Male", "Female", "Rather not say", "Other"], an array, not an array of objects Commented Dec 14, 2020 at 18:28

2 Answers 2

1

Like this?

  {
    $group: {
      _id: null,
      type: {
        $push: "$type"
      }
    }
  },
  {
    $project: {
      _id: 0,
      type: 1
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

1

Try this one:

db.collection.aggregate([
  {
    $group: {
      _id: null,
      type: {
        "$addToSet": "$type"
      }
    }
  }
])

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.