1

I have a function in my MongoDB/Node backend that returns a list of departments.

The documents in the collection look like this:

[
    {
      _id: 111,
      department: "abc"
    },
    {
      _id: 222,
      department: "def"
    },
    {
      _id: 333,
      department: "ghi"
    }
]

This is working with aggregation looks like this:

  $group: {
    _id: null,
    data: { $addToSet: "$department" }
  }

However, what this produces is not ideal. The output looks like this:

{
    "count": 1,
    "data": [
        {
            "_id": null,
            "data": [
                "abc",
                "def",
                "ghi"
            ]
        }
    ]
}

What I'd like to do is return data where there isn't a nested array structure with "data" inside "data". I'd like this output:

{
  "count": 1,
  "data": [
    "abc",
    "def",
    "ghi",
  ]
}

Is there a way I can do this with a projection stage?

I tried this:

  {
    $group: {
      _id: null,
      data: { $addToSet: "$department" }
    }
  },
  {
    $project: {
      data: 0,
      _id: 0
    }
  }

But end up with the same data structure returned. Is there a way I can do this with $project?

UPDATE:

After a suggestion I tried this:

db.staffmembers.aggregate([
      {
        $group: {
          _id: null,
          data: { $addToSet: "$department" }
        }
      },
      {
        $project: {
          data: {
            $reduce: {
              input: "$data.data",
              initialValue: [],
              in: {
                $concatArrays: ["$$this", "$$value"]
              }
            }
          }
        }
      }
    ]);

... but this outputs an empty array for data:

{ 
    "_id" : null, 
    "data" : [

    ]
}
1
  • post some sample data Commented Oct 4, 2018 at 13:57

2 Answers 2

1

This is what you're after:

db.collection.aggregate({
    $project: {
        data: { $arrayElemAt: [ "$data.data", 0 ] },
        _id: 0
    }
})

Mind you, I have a feeling there's something funky about your pipeline and/or data setup. It would probably be beneficial if you could share the input data and the entire pipeline.

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

Comments

0

You can use the $project stage in your pipeline to cherry pick what you require from the previous stage of the aggregation

db.staffmembers.aggregate([
    {
        $group:{
            _id:null,
            data:{$addToSet:"$department"}
        }
    },
    {
        $project:{
            data:1,
            _id:0
        }
    }
])

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.