Reputation: 265
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
Reputation: 19700
One way of doing it would be to use the $redact operator.
name
array, which meet our search criteria.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