3

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.

1

1 Answer 1

2
  • $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

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

5 Comments

I want to sort the results by time, so when exactly should I use these stages inside mine, or maybe I should move the $sort stage to somewhere earlier?
so the skip and limit I should put right before the group, right?
And how do I get the total count of all urls, ignoring the $skip and $limit?
You should add the $limit before the $sort, because the resulting documents must not exceed the BSON Document Size limit of 16 megabytes.
@RonyTesler i have updated answer, i hope you have no more questions after this.

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.