0

I have a document like this:

{
 _id:'5e2b8a2065318f95166deedc'
 expenses:[{amount:100},{amount:200}]
},
{
 _id:'5e2b8a2065318f95166deedc'
 expenses:[]
},
{
 _id:'5e2b8a2065318f95166deedc'
 expenses:[{amount:400},{amount:600}]
}

I need to query with aggregate to return the fields WITH EXPENSES, that is expenses with empty array should not be returned to the next step of the pipeline

This is what I have tried so far:

Exps.aggregate([

    {$match: {"id":ObjectId(myId)}},

    {$group:{
        _id:'$_id',
        expenses:{$last:"$expenses"},
    }}
   ])

But this returns all three subdocuments including the empty one. How can I just get the 1st and 3rd subdocuments (as per my example) so that i can pass them to the next step on the pipeline?

Amani
  • 227
  • 1
  • 10

1 Answers1

0

If expenses has one or more entries, then expenses.1 will exist. Therefore the following would work.

db.collection.aggregate([
  {
    $match: {
      "expenses.1": {
        $exists: true
      }
    }
  }
])

https://mongoplayground.net/p/Hkti0Fj8U3I

Or by using size together with not

db.collection.aggregate([
  {
    $match: {
      "expenses": {
        $not: {
          $size: 0
        }
      }
    }
  }
])

https://mongoplayground.net/p/EpYDtEBf0yk

Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • This https://stackoverflow.com/questions/14789684/find-mongodb-records-where-array-field-is-not-empty which was pointed to me in the comments, solved my problem. Thanks – Amani Feb 12 '20 at 21:19