Question:
How to create a query to unwind the array and filter out elements after an element with a certain value?

Problem

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 only to return elements that come after '3-3' (but also keep 3-3). Any ideas?


Solution

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


db.collection.aggregate([

  { $match: { _id: "123" } },

  {

    $project: {

      _id: 0,

      locations: {

        $slice: [ "$locations", { $indexOfArray: [ "$locations", { uuid: "3-3" } ] }, { $size: "$locations" } ]

      }

    }

  },

  { $unwind: "$locations" },

  { $project: { _id: 0, location: "$locations" } }

])


Answered by: >cmgchess

Credit: >StackOverflow


Blog links:

>How to add a Parsing PHP file in order to get an array of parameters?

>How to correct WordPress site errors after upgrading to PHP 8.2?

>How does Perl match a string containing a dot in PHP?

>How to use PHP to display MySQL results in an HTML table?


Nisha Patel

Nisha Patel

Submit
0 Answers