RFE
RFE

Reputation: 25

mongoDB: Filter array of array

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?

Upvotes: 2

Views: 64

Answers (1)

varman
varman

Reputation: 8894

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

Upvotes: 1

Related Questions