我是mongodb的新手。我正在做使用这个数据库的简单应用程序。这是我的医生收集结构:
{
_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]
}
我想要做的是获得具有所有医生的指定id的治疗的最大值。例如,在这种情况下,如果我想检查_id = 2的处理,它应该返回2500,因为它是用John的对象写的。
任何帮助将不胜感激。感谢。
答案 0 :(得分:1)
将您的收藏命名为stack
试试这个
db.stack.aggregate([ {$project:{"treatments._id":1, "treatments.price":1}},
{$unwind:"$treatments"},{$match:{"treatments._id":2}},
{$sort:{"treatments.price":-1}}, {$limit:1} ]);
结果:{ "_id" : 2, "treatments" : { "_id" : 2, "price" : 2500 } }
参考:https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/