2

I have the following document:

{

   "name": "object1",
   "subarray": [
      {
         "name": "subobject1",
         "list": [
            {
               "date": "2020-01-01",
               "name": "list1"
            }
         ]
      }
   ]
}

I'm trying the following code:

db.getCollection("table").aggregate([
{ "$match": { "name": "object1" } },
{ "$group": { 
    "_id": "$name", 
    "list_array": { 
            "$first": "$subarray.list"
        } 
    } 
}])

The result is the following document:

{
   "_id": "object1",
   "list_array": [
      [
         {
            "date": "2020-01-01",
            "name": "list1"
         }
      ]
   ]
}

I'm getting an array of array but I want something like

{
   "_id": "object1",
   "list_array": [
      {
         "date":"2020-01-01",
         "name":"list1"
      }
   ]
}

My $match will always return only one object. How do I do it?

1 Answer 1

1

With your stages, simply add

{
    "$project": {
      list_array: {
        "$reduce": {
          "input": "$list_array",
          "initialValue": [],
          "in": {
            "$setUnion": [
              "$$this",
              "$$value"
            ]
          }
        }
      }
    }
  }

Working Mongo playground

if you unwind before the group stage, it will also provide expected result Answer with unwind

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

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.