我有一家餐厅,产品和评论收藏
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的餐厅10公里,其产品isAvailable:true和isApproved:true。我还按quantumSold字段对最畅销商品进行了排序。
现在,我还想查询评论最多的产品,并且我希望根据畅销书和评论最多的应用在每个餐厅中仅显示1种商品。然后,在此之后,剩余的产品将随机排列在最畅销和评论最多的产品下方。
实例。我在汉堡王(Burger King),MCDO,Chick-fil-A的10公里内,我将根据畅销书和评论最多的产品(1个产品)看到他们的产品。然后,我将在下面看到他们的所有产品随机化。
当前,您有OPEN(餐厅),APROVED和AVAILABLE项目列表。(您必须调整现有查询的$ project部分以相应地获取更多字段)。
要获得评论,您可以使用$ lookup,其中
{
$lookup:
{
from: "reviews",
localField: "_id",
foreignField: "product",
as: "product_reviews"
}
}
您将获得每个产品的product_reviews数组。然后,您可以执行$ groupby和$ count以在下一个管道阶段获得每个产品的总数。
在聚合管道中获得以上列表后,请按以下方式使用GROUP BY
{$ group:{_id:“ $ restaurant_id”,项目:{$ push:“ $$ ROOT”}}}
(在现有查询的$ project阶段获取产品的餐厅ID和名称)。现在,您有了一个包含餐厅ID /名称及其产品数组的列表。您可以参考以下链接以了解有关$$ ROOT的更多信息
由于您的清单已经排序,因此您将在最上面获得最畅销商品。
关于其他食物,您真的需要每次随机化吗?然后,您可以尝试使用$ sample(请参阅:https : //docs.mongodb.com/manual/reference/operator/aggregation/sample/)或按照您的需要遵循此mongo db聚合随机化(随机播放)结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句