我无法理解如何从数据库中检索四个新售物品。有一个名为Order的模式,它有一个名为item的字段,它只是与此订单一起销售的商品。目前我将订单文件从最新到最旧排序,我对4个订单进行了限制,并检索与这4个最新订单相关的项目。 1个订单只有1个项目。
然而,物品不一定是唯一的。也许这4个最新的订单都是1项。在第一页上有4个确切的项目说这四个是新出售的将是愚蠢的。我考虑过使用distinct(),aggregate,group等,但这些似乎都不符合我的目标。我真的想避免使用蛮力来逐一搜索顺序,直到我得到4个独特的项目。
任何人都可以给我一些暗示如何实现这个目标吗?
Order{
item: {type: ObjectId, ref: "Item"},
date_added: {type: Date, default: Date.now}
}
Item{
name: {type: String},
price: {type: Number}
}
答案 0 :(得分:1)
所以如果一切都在一个集合中,你可以使用它:
db.Order.aggregate([
{$sort: {_id: -1}},
{$group: {
_id: "$item",
firstId: {$first: "$_id"}
}
},
{$sort: {firstId: -1}},
{ $limit: 4 }
])
更新问题后,无法进行此操作。因此,为了复制您的示例,我创建了以下内容:
收藏:order
{
"_id" : ObjectId("5a25361a38f4fb1fc057bb95"),
"item" : ObjectId("5a2535d238f4fb1fc057bb92"),
"date_added" : ISODate("2017-12-04T11:48:42.610+0000")
}
{
"_id" : ObjectId("5a25369a38f4fb1fc057bb9b"),
"item" : ObjectId("5a25367c38f4fb1fc057bb98"),
"date_added" : ISODate("2017-12-04T11:50:50.569+0000")
}
{
"_id" : ObjectId("5a254de038f4fb1fc057bba9"),
"item" : ObjectId("5a254d7438f4fb1fc057bb9e"),
"date_added" : ISODate("2017-12-04T13:30:08.148+0000")
}
{
"_id" : ObjectId("5a254e1f38f4fb1fc057bbb2"),
"item" : ObjectId("5a254d8938f4fb1fc057bba1"),
"date_added" : ISODate("2017-12-04T13:31:38.038+0000")
}
{
"_id" : ObjectId("5a254e6438f4fb1fc057bbb5"),
"item" : ObjectId("5a254d9e38f4fb1fc057bba4"),
"date_added" : ISODate("2017-12-04T13:32:20.244+0000")
}
收藏:item
{
"_id" : ObjectId("5a2535d238f4fb1fc057bb92"),
"name" : "mouse",
"price" : "50"
}
{
"_id" : ObjectId("5a25367c38f4fb1fc057bb98"),
"name" : "keyboard",
"price" : "100"
}
{
"_id" : ObjectId("5a254d7438f4fb1fc057bb9e"),
"name" : "monitor",
"price" : "500"
}
{
"_id" : ObjectId("5a254d8938f4fb1fc057bba1"),
"name" : "mouse",
"price" : "15"
}
{
"_id" : ObjectId("5a254d9e38f4fb1fc057bba4"),
"name" : "headphones",
"price" : "110"
}
因此,根据您的描述,您可以这样做:
db.order.aggregate([
{$sort: {_id: -1}},
{
$lookup:
{
from: "item",
localField: "item",
foreignField: "_id",
as: "items"
}
},
{ $unwind: "$items"},
{
$group:
{
_id: "$items.name",
orderId: {$first: "$_id"},
itemId: {$first: "$item"},
date_added: {$first: "$date_added"},
itemName: {$first: "$items.name"},
itemPrice: {$first: "$items.price"},
}
},
{$sort: {orderId: -1}},
{ $limit: 4 }
])
正如我所说,在你做这一切之前使用$match
是明智之举。像这样举例如:
db.order.aggregate([
{ $match: {"date_added" : {$gte: ISODate("2017-12-04T11:48:43.610+0000")}}},
{$sort: {_id: -1}},
{
$lookup:
{
from: "item",
localField: "item",
foreignField: "_id",
as: "items"
}
},
{ $unwind: "$items"},
{
$group:
{
_id: "$items.name",
orderId: {$first: "$_id"},
itemId: {$first: "$item"},
date_added: {$first: "$date_added"},
itemName: {$first: "$items.name"},
itemPrice: {$first: "$items.price"},
}
},
{$sort: {orderId: -1}},
{ $limit: 4 }
])