0

I am new to mongodb. I am doing simple application that uses this database. Here is my doctors collection structure:

{
    _id: 1,
    name: "David",
    specialisation: "dentist",
    description: "Super dentist",
    treatments: [
        {
            _id: 0,
            price: 2200
        },
        {
            _id: 2,
            price: 200
        },
        {
            _id: 5,
            price: 2500
        },
        {
            _id: 8,
            price: 3200
        },
        {
            _id: 13,
            price: 2050
        }
    ],
    hospitals: [1, 2, 8, 5, 20]
},
{
    _id: 2,
    name: "John",
    specialisation: "dentist",
    description: "Super dentist",
    treatments: [
        {
            _id: 2,
            price: 2500
        }
    ],
    hospitals: [1]
}

What I want to do, is to get the max value of a treatment with specified id of all doctors in collection. For example in this case if I want to check treatment with _id = 2 it should return 2500, as it is written in John's object.

Any help would be appreciated. Thanks.

7
  • In this structure u have to traverse treatments array then do find _id:2 , then keep max price field,then same process for next object and compare max price , this kinda approach vl work but however this seems inefficient structure, how about this treatments:{1:"2200",2:"200",5:"2500",8:"3200",13:"2050"} then u vl be able to do like treatments[2] or treatments:{1:{key1:val1,key2:val2},2:{key1:val1,key2:val2}} tell which approach suits you , vl help u out in that approach's code Commented Nov 7, 2015 at 17:44
  • Unfortunatelly I have to keep this structure. I'm not sure what u mean by 'vl'. Commented Nov 7, 2015 at 17:54
  • sorry my bad , vl->will Commented Nov 7, 2015 at 17:56
  • ahh, ok. I've googled it so far and didn't found any interesting info :D Commented Nov 7, 2015 at 17:59
  • one doubt treatment with _id = 2 it should return 2500, as it is written in John's object here _id=2 u mean outside _id(above name:"john") or the one inside array ? Commented Nov 7, 2015 at 18:00

1 Answer 1

1

Named ur collection as stack try this

db.stack.aggregate([ {$project:{"treatments._id":1, "treatments.price":1}}, 
{$unwind:"$treatments"},{$match:{"treatments._id":2}},
{$sort:{"treatments.price":-1}}, {$limit:1} ]); 

result: { "_id" : 2, "treatments" : { "_id" : 2, "price" : 2500 } }

ref: https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/

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.