0

Right now i have a aggregate pipeline returning the following array:

[{
    "_id": 1,
    "items": {
        "_id": 1,
        "transactions": []
    }
  },
{
    "_id": 2,
    "items": {
        "_id": 2,
        "transactions": [
            {
                "_id": "5a536dc1bc9b2113986a9047",
                "price": 5.56
            },
            {
                "_id": "5a536e1bbc9b2113986a904e",
                "price": 11.56,
            }
        ]
    }
},
{
    "_id": 3,
    "items": {
        "_id": 1,
        "transactions": []
    }
}]

It is possible to filter the documents where the field "transactions" in subdocument "items" is not empty. Like this:

[{
    "_id": 2,
    "items": {
        "_id": 2,
        "transactions": [
            {
                "_id": "5a536dc1bc9b2113986a9047",
                "price": 5.56
            },
            {
                "_id": "5a536e1bbc9b2113986a904e",
                "price": 11.56,
            }
        ]
    }
}]

Is for aggregate pipeline not for query

Saravana
  • 12,647
  • 2
  • 39
  • 57
cabef
  • 5
  • 4
  • Possible duplicate of [Query for documents where array size is greater than 1](https://stackoverflow.com/questions/7811163/query-for-documents-where-array-size-is-greater-than-1) – s7vr Jan 08 '18 at 21:11
  • Add last stage as `{"$match":{'items.transactions.1': {$exists: true}}}` – s7vr Jan 08 '18 at 21:11
  • This works but, i change the 1 for 0, for when these elements have at least one element. But I still do not understand it at all, how it works – cabef Jan 08 '18 at 21:28
  • Not sure what you are asking. Here is some more explanation from [docs](https://docs.mongodb.com/manual/tutorial/query-arrays/#query-for-an-element-by-the-array-index-position) if it helps. – s7vr Jan 08 '18 at 21:54

1 Answers1

0

In your aggregate pipeline, add $match pipeline in last to filter based on the transaction array size

> db.foo.aggregate([{$match : {"items.transactions" : { $gt : {$size : 0}}}}]).pretty()

output

{
    "_id" : 2,
    "items" : {
        "_id" : 2,
        "transactions" : [
            {
                "_id" : "5a536dc1bc9b2113986a9047",
                "price" : 5.56
            },
            {
                "_id" : "5a536e1bbc9b2113986a904e",
                "price" : 11.56
            }
        ]
    }
}
> 

sample documents

> db.foo.find().pretty()
{ "_id" : 1, "items" : { "_id" : 1, "transactions" : [ ] } }
{
    "_id" : 2,
    "items" : {
        "_id" : 2,
        "transactions" : [
            {
                "_id" : "5a536dc1bc9b2113986a9047",
                "price" : 5.56
            },
            {
                "_id" : "5a536e1bbc9b2113986a904e",
                "price" : 11.56
            }
        ]
    }
}
{ "_id" : 3, "items" : { "_id" : 1, "transactions" : [ ] } }
> 
Saravana
  • 12,647
  • 2
  • 39
  • 57