I have a document like this in a collection:
{
_id: '123',
locations: [
{uuid:'1-1'},
{uuid:'2-2'},
{uuid:'3-3'},
{uuid:'4-4'}
]
}
I would like to create a query that returns this:
[
{ location: { uuid:'3-3'} }
{ location: { uuid:'4-4'} }
]
Looks like a job for aggregate
Start off by:
{ $match: { _id: 123 } }
then maybe
{ $unwind: '$locations' }
then
{ $project: { _id: 0, location: '$locations'} }
Cool, this gives me:
[
{ location: { uuid: '1-1'} }
{ location: { uuid: '2-2'} }
{ location: { uuid: '3-3'} }
{ location: { uuid: '4-4'} }
]
Now i need a way to only return elements that come after ‘3-3’ (but also keep 3-3). Any ideas?
2
Answers
Here the approach I took is to
$slice
the array from index 2 to end of array so to get the position of 3-3 i used$indexOfArray
.Now since locations is sliced there is fewer to
$unwind
demo
The accepted answer works but for extra protection, you might want to do
$indexOfArray
on theuuid
target, not the object:This ensures correct matching on only
uuid
. For example, assume the input objects are more complex and possibly polymorphic:Then the original approach:
will fail because of additional fields
baz
andnot_concerned
.