【发布时间】:2021-03-19 08:41:06
【问题描述】:
我收藏了餐厅、产品和评论
restaurants: [
{
_id: 1,
name: "Burger King",
location: {
type: "Point",
coordinates: [
11.111,
11.111
]
},
isOpen: true
},
{
_id: 2,
name: "McDonald's",
location: {
type: "Point",
coordinates: [
22.222,
22.222
]
},
isOpen: true
},
{
_id: 3,
name: "Chick-fil-A",
location: {
type: "Point",
coordinates: [
33.333,
33.333
]
},
isOpen: true
}
],
products: [
{
_id: 1,
name: "Breakfast Whopper Jr.",
price: "$1.29",
isAvailable: true,
isApproved: true,
quantitySold: 50,
restaurant: ObjectId("1")
},
{
_id: 2,
name: "Big Mac",
price: "$4.35",
isAvailable: true,
isApproved: true,
quantitySold: 59,
restaurant: ObjectId("2")
},
{
_id: 3,
name: "Spicy Chicken Sandwich",
price: "$3.29",
isAvailable: true,
isApproved: true,
quantitySold: 60,
restaurant: ObjectId("3")
},
{
_id: 4,
name: "Chicken Sandwich",
price: "$2.29",
isAvailable: true,
isApproved: true,
quantitySold: 58,
restaurant: ObjectId("3")
}
],
reviews: [
{
_id: 1,
message: "Big burger even if it's junior size.",
restaurant: ObjectId("1"),
product: ObjectId("1")
},
{
_id: 2,
message: "Big Mac is really the best burger in town.",
restaurant: ObjectId("2"),
product: ObjectId("2")
},
{
_id: 3,
message: "Spicy Chicken Sandwich rocks!",
restaurant: ObjectId("3"),
product: ObjectId("3")
},
{
_id: 4,
message: "Chicken Sandwich is the best sandwich of Chick-fil-A!",
restaurant: ObjectId("3"),
product: ObjectId("4")
},
{
_id: 5,
message: "Chicken Sandwich is the best!",
restaurant: ObjectId("3"),
product: ObjectId("4")
}
]
我的实现
db.products.aggregate([
{
$lookup: {
"from": "restaurant",
"localField": "restaurant",
"foreignField": "_id",
"as": "restaurant"
}
},
{
$match: {
"restaurant.isOpen": true,
"isApproved": true,
"isAvailable": true
}
},
{
$project: {
"restaurant.isOpen": 1,
"isApproved": 1,
"isAvailable": 1,
"restaurant.location": 1,
"quantitySold": 1
}
},
{
$match: {
"restaurant.location": {
$geoWithin: {
$centerSphere: [[222.22, 222.33], 10/6378.1] // sample coordinates
}
}
}
},
{
$sort: {
// best seller
"quantitySold": -1
}
}
在我的实现中。我目前正在获得 isOpen: true 及其产品 isAvailable: true 和 isApproved: true 的 10 公里餐厅。我还按 quantitySold 字段对最畅销的商品进行了排序。
现在,我还想查询评论最多的产品,并且我想根据畅销书和评论最多的产品在我的应用中仅显示每家餐厅的 1 件产品。然后,剩下的产品将随机排列在最畅销和评论最多的下面。
示例。我在汉堡王、MCDO、Chick-fil-A 的 10 公里处,我会根据畅销书和评论最多的产品(1 个产品)查看他们的产品。然后,我会在下面看到他们所有的产品随机化。
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework