无法使用 mongo shell 找到 MongoDB 的正确查询
Can't find right query for MongoDB using mongo shell
我一直在尝试获取包含每种药物的最新(根据其成立日期)药房的清单。
以下面文档数组的结果为例:
Output:
Medicine : MedA , Pharmacy : a
Medicine : MedB , Pharmacy : b
Medicine : MedC , Pharmacy : b
Medicine : MedD , Pharmacy : a
[
{
"Pharmacy": "a",
"EstablishedDate": ISODate("2006-10-12"),
"Medicine": [
{
"MedName": "MedA",
"Quantity": 55
},
{
"MedName": "MedB",
"Quantity": 34
},
{
"MedName": "MedD",
"Quantity": 25
}
]
},
{
"Pharmacy": "b",
"EstablishedDate": ISODate("2015-2-2"),
"Medicine": [
{
"MedName": "MedB",
"Quantity": 60
},
{
"MedName": "MedC",
"Quantity": 34
}
]
}
]
如何解决?
1.Answer 各个药房的所有药品
db.collection.aggregate([
{
$unwind: "$Medicine"
},
{
$project: {
"_id": 0,
"Medicine": "$Medicine.MedName",
"Pharmacy": "$Pharmacy"
}
}
])
输出
[
{
"Medicine": "MedA",
"Pharmacy": "a"
},
{
"Medicine": "MedB",
"Pharmacy": "a"
},
{
"Medicine": "MedD",
"Pharmacy": "a"
},
{
"Medicine": "MedB",
"Pharmacy": "b"
},
{
"Medicine": "MedC",
"Pharmacy": "b"
}
]
参考playground和运行脚本
2.All 有最新药房的药品
db.collection.aggregate([
{
$unwind: "$Medicine"
},
{
$sort: {
EstablishedDate: -1
}
},
{
$group: {
_id: "$Medicine.MedName",
Pharmacy: {
$first: "$Pharmacy"
}
}
},
{
$project: {
_id: 0,
"Medicine": "$_id",
"Pharmacy": "$Pharmacy"
}
}
])
输出
[
{
"Medicine": "MedA",
"Pharmacy": "a"
},
{
"Medicine": "MedC",
"Pharmacy": "b"
},
{
"Medicine": "MedD",
"Pharmacy": "a"
},
{
"Medicine": "MedB",
"Pharmacy": "b"
}
]
分别参考playground和运行脚本
我一直在尝试获取包含每种药物的最新(根据其成立日期)药房的清单。
以下面文档数组的结果为例:
Output:
Medicine : MedA , Pharmacy : a
Medicine : MedB , Pharmacy : b
Medicine : MedC , Pharmacy : b
Medicine : MedD , Pharmacy : a
[
{
"Pharmacy": "a",
"EstablishedDate": ISODate("2006-10-12"),
"Medicine": [
{
"MedName": "MedA",
"Quantity": 55
},
{
"MedName": "MedB",
"Quantity": 34
},
{
"MedName": "MedD",
"Quantity": 25
}
]
},
{
"Pharmacy": "b",
"EstablishedDate": ISODate("2015-2-2"),
"Medicine": [
{
"MedName": "MedB",
"Quantity": 60
},
{
"MedName": "MedC",
"Quantity": 34
}
]
}
]
如何解决?
1.Answer 各个药房的所有药品
db.collection.aggregate([
{
$unwind: "$Medicine"
},
{
$project: {
"_id": 0,
"Medicine": "$Medicine.MedName",
"Pharmacy": "$Pharmacy"
}
}
])
输出
[
{
"Medicine": "MedA",
"Pharmacy": "a"
},
{
"Medicine": "MedB",
"Pharmacy": "a"
},
{
"Medicine": "MedD",
"Pharmacy": "a"
},
{
"Medicine": "MedB",
"Pharmacy": "b"
},
{
"Medicine": "MedC",
"Pharmacy": "b"
}
]
参考playground和运行脚本
2.All 有最新药房的药品
db.collection.aggregate([
{
$unwind: "$Medicine"
},
{
$sort: {
EstablishedDate: -1
}
},
{
$group: {
_id: "$Medicine.MedName",
Pharmacy: {
$first: "$Pharmacy"
}
}
},
{
$project: {
_id: 0,
"Medicine": "$_id",
"Pharmacy": "$Pharmacy"
}
}
])
输出
[
{
"Medicine": "MedA",
"Pharmacy": "a"
},
{
"Medicine": "MedC",
"Pharmacy": "b"
},
{
"Medicine": "MedD",
"Pharmacy": "a"
},
{
"Medicine": "MedB",
"Pharmacy": "b"
}
]
分别参考playground和运行脚本