我从mongodb聚合查询得到响应,并面临聚合查询的格式问题。
下面是我的mongodb聚合查询:
const result = await RegistrationForm.aggregate([
// 1. Get Register Forms
{
$match: {
"_id": mongoose.Types.ObjectId(req.query.saheli_num),
"is_deleted": false,
"date": {
"$gte": new Date(moment(req.query.start_date, "YYYY-MM-DD").startOf("day")),
"$lte": new Date(moment(req.query.end_date, "YYYY-MM-DD").endOf("day")),
}
}
},
// 2. Get Update Forms
{
$lookup: {
"from": "update_forms",
"localField": "_id",
"foreignField": "register_form_id",
"as": "update_form"
}
},
// 3. Merge Both Register Forms and Update Forms
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$update_form", 0 ] }, "$$ROOT" ] } }
},
]);
我在附加了一个数组的合并对象中得到响应。
以下是汇总结果
[
{
_id: "634e9f99f906a707bec7beb1",
date: "2021-10-18T00:00:00.000Z",
first_name: "Daniel",
last_name: "Spenser",
staff_name: "john",
is_deleted: false,
update_form: [
{
_id: "63831c2d26c1318c7094d473",
date: "2022-03-11T00:00:00.000Z",
first_name: "Kylee",
last_name: "Arroyo",
staff_name: "john"
is_deleted: false,
},
{
_id: "63831c3f26c1318c7094d485",
date: "2022-09-15T00:00:00.000Z",
first_name: "Forbes",
last_name: "Randall",
staff_name: "john"
is_deleted: false,
}
]
}
]
我想将汇总结果格式化为所需表格格式,如下所示
[
{
_id: "634e9f99f906a707bec7beb1",
date: "2021-10-18T00:00:00.000Z",
first_name: "Daniel",
last_name: "Spenser",
staff_name: "john",
is_deleted: false,
},
{
_id: "63831c2d26c1318c7094d473",
date: "2022-03-11T00:00:00.000Z",
first_name: "Kylee",
last_name: "Arroyo",
staff_name: "john",
is_deleted: false,
},
{
_id: "63831c3f26c1318c7094d485",
date: "2022-09-15T00:00:00.000Z",
first_name: "Forbes",
last_name: "Randall",
staff_name: "john",
is_deleted: false,
}
]
1条答案
按热度按时间5vf7fwbs1#
使用
$unionWith
来得到结果,这样就不需要$lookup
和$unwind
了,这样会不会更简单?Mongo Playground