1

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?

1 Answer 1

2

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"
                      ] 
            }

}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.