猫鼬查询中的嵌套选择
Posted
技术标签:
【中文标题】猫鼬查询中的嵌套选择【英文标题】:Nested select in Mongoose Query 【发布时间】:2020-08-11 13:22:01 【问题描述】:我正在尝试将 SQL 转换为 Mongoose 查询,但我发现它很混乱。这是我的架构。基本上我想从今天开始获取过去 7 天的数据
var mongoose = require('mongoose');
var RequestSchema = new mongoose.Schema(
pickup_person_name:String,
dest_person_name:String,
pickup_person_phone:String,
dest_person_phone:String,
tranx_status:String,
order_status:String,
pickup_longitude:String,
pickup_latitude:String,
pickup_location_name:String,
pickup_date:Date,
dest_longitude:String,
dest_latitude:String,
dest_location_name:String,
price:String,
item_to_deliver:String,
rider_id:String,
rider_name:String,
order_number:String,
payment_mode:String
, autoCreate: true);
mongoose.model('Request', RequestSchema);
这是我要转换为 Mongoose 的查询。
SELECT pickup_date, count(*) FROM (SELECT pickup_date as event_date FROM requests where DATE(pickup_date) >= (CURRENT_DATE - '7 DAYS') ) GROUP BY pickup_date ORDER BY pickup_date
I expect to have a list like
[ event_date:27/08/2020,count:8, event_date:26/08/2020,count:9, event_date:25/08/2020,count:9]
【问题讨论】:
你能从你的数据库中发布数据吗? 我希望从数据库 [ event_date:27/08/2020,count:8, event_date:26/08/2020,count:9, event_date: 25/08/2020,count:9] 【参考方案1】:你想使用这样的东西:
db.collection.aggregate([
$match:
$expr:
$gte: [
"$pickup_date",
"$subtract": [
"$$NOW",
604800000
]
]
,
$group:
_id:
year:
$year: "$pickup_date"
,
month:
$month: "$pickup_date"
,
day:
"$dayOfMonth": "$pickup_date"
,
count:
$sum: 1
,
$project:
count: 1,
_id: 0,
event_date:
"$concat": [
"$toString": "$_id.day"
,
"/",
"$toString": "$_id.month"
,
"/",
"$toString": "$_id.year"
]
])
MongoPlayground
【讨论】:
我的 order_status 为 Done,New。对于那些日期。我想将它们添加到数组中,以便我们得到 [ event_date:27/08/2020,count:8,new:2,done:1, event_date:26/08/2020,count:9,,new :1,done:1, event_date:25/08/2020,count:9,,new:2,done:1] 我将如何将其添加到聚合中。您的查询有效 像这样:mongoplayground.net/p/b791bTa0nXG以上是关于猫鼬查询中的嵌套选择的主要内容,如果未能解决你的问题,请参考以下文章