[SERVER-44441] aggregation framework should have a $find expression Created: 05/Nov/19  Updated: 06/Dec/22

Status: Backlog
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: 4.2.1
Fix Version/s: None

Type: New Feature Priority: Minor - P4
Reporter: Ben Rotz Assignee: Backlog - Query Optimization
Resolution: Unresolved Votes: 2
Labels: expression, qopt-team
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
is duplicated by SERVER-44957 Proposal: $find aggregation pipeline ... Closed
Assigned Teams:
Query Optimization
Participants:

 Description   

Aggregation framework has a filter, which filters an array (and returns an array).

I wish there was an equivalent to do a javascript Array.find(), where the filter would return the first match inside of the array

db.test.insert({people: [{name: 'bob', value: 1}, {name: 'fred', value: 2}]});
 
db.test.aggregate([{$addFields: {
  person: {
    $find: {
      input: '$people',
      cond: {$eq: ['$$this.name', 'fred']}
    }
  },
  people: '$$REMOVE'
}}]);
 
##returns
{person: {name: 'fred', value: 2}}

 



 Comments   
Comment by Asya Kamsky [ 05/Nov/19 ]

ben@ethika.com you can do it already with this combination of expressions:

db.test.aggregate({$addFields:{
   person:{
      $arrayElemAt:[ 
         "$people", 
         {$indexOfArray:["$people.name","fred"]}
      ]
   }
}})

I'm not sure "$find" is a preferred term due to possible confusion with find command, but I will set this to be considered by the query team.

Comment by Asya Kamsky [ 05/Nov/19 ]

You can always use $arrayElemAt expression to select the first element from array (whether it has one element or not). But it makes sense to have a simple way to pick out first element that matches a particular condition. I’ll check if there’s already a ticket for this.

Comment by Ben Rotz [ 05/Nov/19 ]

Oops, the return should obviously be `{person: {name: 'fred', value: 2}}`

Generated at Thu Feb 08 05:05:59 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.