Jason Z
Jason Z

Reputation: 265

MongoDB how to return multiple data in an array

I have some data like

{"name":[{"age":15},{"age":18},{"age":20}]}

I want search age greater than 17, here is my script

db.test.find({"name.age":{"$gt":17}},{"name.age.$":1})

This will return

{"name":[{"age":18}]}

But I want get all data greater than 18

How to improve the script?

Upvotes: 1

Views: 108

Answers (1)

BatScream
BatScream

Reputation: 19700

One way of doing it would be to use the $redact operator.

  • Match all the records which have at least one sub document in the name array, which meet our search criteria.
  • Keep only those sub documents in the name array, which are a match.

snippet:

var minimumAge = 17;
db.t.aggregate([
{$match:{"name.age":{$gt:minimumAge}}},
{$redact:{$cond:[
                 {$gt:[{$ifNull:["$age",minimumAge+1]},
                        minimumAge]},
                        "$$DESCEND",
                        "$$PRUNE"
                      ] 
            }

}
])

Upvotes: 2

Related Questions