Reputation: 13
I'm trying to slice a deeply nested array. Take the structure below as an example. I need to slice this array for pagination.
{messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah2} ] }]}
How would I use the slice operator in this scenario?
Here is an example of my current query shown below.
model.findOne({query: query}, { 'messages.0.message.members': { '$slice': [ 0, 10 ] } })
Then I return the document but the members length remains 14 when I'm slicing the array to return only the first 10 members of the array.
This may not even be possible but I would like to include the slice in the query to limit any other logic that might slow it down.
Any help with this would be greatly appreciated. Thanks!
Upvotes: 1
Views: 1052
Reputation: 17915
I'm not sure whether it's easy or not to do it through .find()
- As we know it's not working is because of embedded arrays, Please try this :
db.YourCollectionName.aggregate([{ $match: { "_id": ObjectId("5df94e17400289966e8707a7") } },
/** You can use $addFields if you want to retain remaining fields */
{ $project: { 'messages': { $arrayElemAt: ["$messages", 0] } } },
{ $project: { members: '$messages.message.members' } },
{ $project: { membersArr: { '$slice': ['$members', 0, 2] } } }])
Result :
/* 1 */
{
"_id" : ObjectId("5df94e17400289966e8707a7"),
"membersArr" : [
{
"example" : "object",
"blah" : "blah"
},
{
"example2" : "object2",
"blah2" : "blah2"
}
]
}
Collection Data :
/* 1 */
{
"_id" : ObjectId("5df94e17400289966e8707a7"),
"messages" : [
{
"message" : {
"members" : [
{
"example" : "object",
"blah" : "blah"
},
{
"example2" : "object2",
"blah2" : "blah2"
},
{
"example2" : "object3",
"blah2" : "blah3"
},
{
"example2" : "object4",
"blah2" : "blah4"
}
]
}
},
{
"message" : {
"members" : [
{
"example" : "object11",
"blah" : "blah11"
},
{
"example2" : "object211",
"blah2" : "blah211"
},
{
"example2" : "object311",
"blah2" : "blah311"
},
{
"example2" : "object411",
"blah2" : "blah411"
}
]
}
}
]
}
/* 2 */
{
"_id" : ObjectId("5df94e28400289966e870b34"),
"messages" : [
{
"message" : {
"members" : [
{
"example" : "objectF",
"blah" : "blah"
},
{
"example2" : "objectF2",
"blah2" : "blah2"
},
{
"example2" : "objectF3",
"blah2" : "blah3"
},
{
"example2" : "objectF4",
"blah2" : "blah4"
}
]
}
}
]
}
Ref : $addFields , $arrayElemAt , $slice
Upvotes: 2