skip to Main Content

I have written a MongoDB query that looks like this:

db.collection.aggregate([
  {
    $group: {
      _id: null,
      categories: {
        $addToSet: "$category"
      }
    }
  },
  {
    $project: {
      _id: 0,
      categories: 1
    }
  }
])

but the result is:

[
  {
    "categories": [
      "Enhancement",
      "Bug"
    ]
  }
]

how can I get a result like this:

["Enhancement", "Bug"]

mongodb playground

2

Answers


  1. You can maybe try to modify the query to include an additional aggregation stage using $unwind and $replaceRoot operators. Tell me if it works for you.

     db.collection.aggregate([
          {
            $group: {
              _id: null,
              categories: {
                $addToSet: "$category"
              }
            }
          },
          {
            $unwind: "$categories"
          },
          {
            $replaceRoot: {
              newRoot: "$categories"
            }
          }
        ])
    
    Login or Signup to reply.
  2. MongoDB is a document database, it will always return a document or an array of documents. There is no query method in MongoDB that will return a scalar value or an array of scalar values.

    You can do modification on the client side. If you are using javascript, you could get that result with:

    db.collection.aggregate([
      {
        $group: {
          _id: null,
          categories: {
            $addToSet: "$category"
          }
        }
      },
      {
        $project: {
          _id: 0,
          categories: 1
        }
      }
    ])[0].categories
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search