1

Lets say I have a collection of the following documents:

{
  _id,
  profile: {...},
  arrayProp1: [....],
  arrayProp2: [....],
  arrayProp3: [....],
  ...
}

Number of objects in arrayPropX arrays may be become big, at least thousands. So I need to use pagination and the question is what is the best way to do this?

For example how to return:

  1. Total number of elements in arrayProp1 for specified _id
  2. X elements from position Y in arrayProp1 for specified _id ?

Same as above but with filter on some field on arrayProp1 elements?

1 Answer 1

1

You need two operators: $size and $slice:

db.collection.aggregate([
    {
        $match: { _id: queryId }
    },
    {
        $project: {
            _id: 1,
            size: { $size: "$arrayProp1" } 
        }
    }
])

db.collection.aggregate([
    {
        $match: { _id: queryId }
    },
    {
        $project: {
            _id: 1,
            sliced: { $slice: ["$arrayProp1", Yposition, Xelements] } 
        }
    }
])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it works fine, but what if I need to sort array before slice? Looks like it is not possible without $unwind first?
@ДмитрийАлферьев that is correct, you have to $unwind - sorting inner array is one of the features I would like to have in MongoDB

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.