如何使用MongoDb聚合3个集合的计数/总和?
我正在尝试聚合多个集合,并根据如何使用MongoDb聚合3个集合的计数/总和?,mongodb,sum,aggregation-framework,lookup,Mongodb,Sum,Aggregation Framework,Lookup,我正在尝试聚合多个集合,并根据createdAt字段获取每日总计: db={ "agents": [ { "_id": ObjectId("5a934e000ac2030405000370"), "name": "Book Now" } ], "tolls": [ { "_id": Ob
createdAt
字段获取每日总计:
db={
"agents": [
{
"_id": ObjectId("5a934e000ac2030405000370"),
"name": "Book Now"
}
],
"tolls": [
{
"_id": ObjectId("5a934e000102030405000000"),
"amountCollected": 20,
"plaza": "Shimabala",
"directionLane": "South/3",
"cashier": "Chishala",
"agent": {
"_id": ObjectId("5a934e000ac2030405000370"),
"name": "Book Now"
},
"createdAt": ISODate("2021-06-02T13:23:06.232Z")
},
{
"_id": ObjectId("a9934ec001a203040500dc00"),
"amountCollected": 150,
"plaza": "Shimabala",
"directionLane": "South/3",
"cashier": "Chishala",
"agent": {
"_id": ObjectId("5a934e000ac2030405000370"),
"name": "Book Now"
},
"createdAt": ISODate("2021-06-04T13:23:06.232Z")
}
],
"fuel": [
{
"_id": ObjectId("60b79e4e4afd77a1c27c730c"),
"litres": 5.2,
"price": 90,
"station": "Chilanga",
"fuelAttendant": "Manda",
"agent": {
"_id": ObjectId("5a934e000ac2030405000370"),
"name": "Book Now"
},
"createdAt": ISODate("2021-06-04T16:06:16.232Z")
}
]
}
预期成果:
[
{
"_id": "2021-06-02",
"fuel": 0,
"tolls": 1
},
{
"_id": "2021-06-04",
"fuel": 1,
"tolls": 1
}
]
因为两个集合连接到代理的集合,所以我有这个查询,但不确定如何从那里开始:
db.agents.aggregate([
{
"$lookup": {
"localField": "_id",
"from": "tolls",
"foreignField": "agent._id",
"as": "tolls"
}
},
{
"$unwind": {
"path": "$tolls",
"preserveNullAndEmptyArrays": true
}
},
{
"$lookup": {
"localField": "_id",
"from": "fuel",
"foreignField": "agent._id",
"as": "fuel"
}
},
{
"$unwind": {
"path": "$fuel",
"preserveNullAndEmptyArrays": true
}
}
])
- 从
收费查询
收费
显示必填字段并为“通行费”添加新字段$project
with$unionWith
采集和fuel
显示必填字段为“fuel”添加新字段$project
类型
- 现在,我们在根目录中合并了两个集合文档,并为每个文档添加了
type
按$group
和日期
计算元素总数类型
仅按$group
进行分组,并使用其日期
键值格式构造这两种计数
的数组类型
使用$addFields
$arrayToObject
[
{
"_id": "2021-06-04",
"analytic": {
"fuel": 1,
"tolls": 1
}
},
{
"_id": "2021-06-02",
"analytic": {
"tolls": 1
}
}
]
这不会添加0计数字段,您必须在前端/客户端对其进行管理
[
{
"_id": "2021-06-04",
"analytic": {
"fuel": 1,
"tolls": 1
}
},
{
"_id": "2021-06-02",
"analytic": {
"tolls": 1
}
}
]