Rony Tesler
Rony Tesler

Reputation: 1401

mongodb - concat array field from many documents to one array field

I have this query:

 [
  {
    '$match': {
      'imageUrls': {
        '$type': 'array', 
        '$ne': []
      }
    }
  }, {
    '$project': {
      'imageUrls': 1, 
      'time': 1
    }
  }, {
    '$sort': {
      'time': 1
    }
  }, {
    '$skip': 0
  }, {
    '$limit': 10
  }
]

This is the schema:

{
    "_id": {
        "$oid": "5ffb0c14dd482daa039ee906"
    },
    "imageUrls": ["image url1", "image url2"],
    "time": 342432432432
}

The output is a list of documents, each containing the array field imageUrls. I want to have all the values in the imageUrls fields in one single array field.

Upvotes: 3

Views: 732

Answers (1)

turivishal
turivishal

Reputation: 36104

  • $sort by time in descending order
  • $project to show only one field imageUrls
  • $unwind deconstruct imageUrls array
  • $facet to separate both result, total and pagination documents
  • $skip documents
  • $limit number of documents
  • $group by null and reconstruct imageUrls array
  { $sort: { time: -1 } },
  { $project: { imageUrls: 1 } },
  { $unwind: "$imageUrls" },
  {
    $facet: {
      result: [
        { $skip: 0 },
        { $limit: 10 },
        {
          $group: {
            _id: null,
            imageUrls: { $push: "$imageUrls" }
          }
        }
      ],
      count: [
        { $count: "count" }
      ]
    }
  }

Playground

Upvotes: 2

Related Questions