0

I'm looking for a solution to get the first entry that match my condition. Actually, I made an $unwind on the contribution collection, thne a $sort on the contributionDate and I get data like this :

"contributions" : {      
    "cuid" : "cjibozq4200aw0ltii23cqqdw",           
    "contributionDate" : ISODate("2018-06-12T12:58:31.530+0000"), 
    "hours" : 0, 
    "items" : 0, 
    "money" : 16.5, 
    "currency" : "chf", 
    "
},
"contributions" : {      
    "cuid" : "cdasd200lasikks",           
    "contributionDate" : ISODate("2019-06-12T12:58:31.530+0000"), 
    "hours" : 10, 
    "items" : 0, 
    "money" : 0, 
    "
}

Now my goal is to have the first time my user make a contribution with hours and with money. For that, I've got :

firstDonation : {
$first: { 
    $cond: [ { $and: [ { $gt: [ "$contributions.money", 0 ]}, { $not: "$contributions.rejectionDate" }] }, {
       $dateToString: {
          "date": "$contributions.contributionDate",
          "format": "%d.%m.%Y",
          onNull: '$noVal'
          }           
       }, "" ]
    }
},
firstVolunteering : {
$first: { 
    $cond: [ { $and: [ { $gt: [ "$contributions.items", 0 ]}, {  }] }, {
       $dateToString: {
          "date": "$contributions.contributionDate",
          "format": "%d.%m.%Y",
          onNull: '$noVal'
          }           
       }, "yes" ]}
},

But this is not working as expected. I didn't use the $cond the right way. My wish is to conditionally add to firstDonation the $first result that have $contributions.money > 0.

Kaherdin
  • 1,321
  • 2
  • 14
  • 25
  • There was no need to `$unwind` or even use `aggregate()`. The **first match** is the default behavior of the [positional operator `$`](https://docs.mongodb.com/manual/reference/operator/projection/positional/). See the answers that use it for more direction. The "multiple conditions" would use [`$elemMatch`](https://docs.mongodb.com/manual/reference/operator/query/elemMatch/) in the query portion. Again see the answers that use it, or even the [documentation](https://docs.mongodb.com/manual/tutorial/query-array-of-documents/#specify-multiple-conditions-for-array-of-documents) – Neil Lunn Oct 03 '19 at 02:25
  • Thanks, it helps me. – Kaherdin Oct 03 '19 at 14:42

0 Answers0