鉴于以下文件......
{ "_id": ObjectId("56116d8e4a0000c9006b57ac"), "name": "Stock 1", "items" [
{ "price": 1.50, "desc": "Item 1" }
{ "price": 1.70, "desc": "Item 2" }
{ "price": 1.10, "desc": "Item 3" }
]
}
我希望得到价格最低的商品。以下是我尝试将价格从最低到最高排序:
db.stock.wip.aggregate([
{$unwind: "$items"},
{$sort: {"items.price":1}},
{$group: {_id:"$_id", items: {$push:"$items"}}}
]);
......结果如下:
"result" : [
{
"_id" : ObjectId("56116d8e4a0000c9006b57ac"),
"items" : [
{
"price" : 1.10,
"desc" : "Item 3"
},
{
"price" : 1.50,
"desc" : "Item 1"
},
{
"price" : 1.70,
"desc" : "Item 2"
}
]
}
],
"ok" : 1
我如何获得第3项(最便宜的)?这是我正在寻找的结果:
{
"price" : 1.10,
"desc" : "Item 3"
}
答案 0 :(得分:1)
使用$ first运算符而不是$ push,然后执行$ project:
db.stock.wip.aggregate([
{$unwind: "$items"},
{$sort: {"items.price":1}},
{$group: {_id:"$_id", items: {$first:"$items"}}},
{ $project: {
_id: 0,
price: "$items.price",
desc: "$items.desc",
}}
]);
如果您想仅将结果限制在集合的第一项,请在$ sort后添加{$ limit:1}运算符:
db.stock.wip.aggregate([
{$unwind: "$items"},
{$sort: {"items.price":1}},
{$limit:1},
{$group: {_id:"$_id", items: {$first:"$items"}}},
{ $project: {
_id: 0,
price: "$items.price",
desc: "$items.desc",
}}
]);
答案 1 :(得分:1)
我设法从您自己开始编写聚合查询,稍微更改了$group
阶段并添加了额外的$project
步骤:
db.stock.wip.aggregate([
{$unwind: "$items"},
{$sort: {"items.price":1}},
{$group: {
_id:null,
lowestItem: {$first:"$items"}}},
{$project: {_id: 0, price: "$lowestItem.price", desc: "$lowestItem.desc"}}
]);