0

I have a hard time understanding how to do queries on arrays. A basic example, If I take this document:

Man
 children
  Frank
   age: 33
  Anna
   age: 28

How do I find all the children who have an age greater than 30?

Thanks!

Anna
  • 839
  • 2
  • 17
  • 33
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – s7vr Jan 03 '18 at 12:50
  • 1
    Something like `db.collection_name.aggregate([ {$match: {'children.age': {$gt:30}}, {$project: { children: {$filter: { input: '$children', as: 'child', cond: {$gt: ['$$child.age', 30]} }}, _id: 0 }} ])` – s7vr Jan 03 '18 at 12:52

1 Answers1

0

The query of @Veeram works pretty well:

db.getCollection('men').aggregate([ 
{ $match: {'children.age': {$gt:30}} }, 
{ $project: { children: {$filter: { input: '$children', as: 'child', cond: {$gt: ['$$child.age', 30]} }}, _id: 0 }}
])

This link helped me to understand.

Anna
  • 839
  • 2
  • 17
  • 33
  • 1
    I think you meant $$child.age but that's OK. For clarity, the $match will find all docs where at least one of the children is > 30, but that will yield the whole doc with the whole child array possibly including children <= 30. So the $filter is required to weed out <= 30. – Buzz Moschetti Jan 03 '18 at 15:26
  • Thank you @BuzzMoschetti – Anna Jan 04 '18 at 08:12