如何解决如何按MongoDB中的特定字段对文档进行分组
目前,我有一个收藏集 book_orders 如下:
{
"order_id" : 1,"customer_name": "Nikos","order_type": "digital","title": "Zorba","price": 25
}
{
"order_id" : 2,"customer_id": "Giorgos","order_type": "physical_delivery","title": "War and Peace","price": 30
}
{
"order_id" : 2,"title": "Children of the Gabalawi Street","price": 35
}
{
"order_id" : 3,"title": "The Desert of the Tartars","price": 40
}
我要使用此集合,是要有一个这样的输出,其中我按order_id
对订单进行分组,然后将它们嵌入到名为digital_orders
和physical_orders
的列表中通过随后按order_type
分组。
我认为我需要使用聚合,但是我不确定该怎么做。我必须保留customer_name
,title
和price
之类的字段,这一点很重要。任何帮助表示赞赏。
{
"order_id": 1,"digital_orders": [
{
"title": "Zorba","price": 25
}
],"physical_orders": []
},{
"order_id": 2,"customer_name": "Giorgos","digital_orders": [
{
"title": "War and Peace","total": 25
}
],"physical_orders": [
{
"title": "Children of the Gabalawi Street","price": 35
}
]
},{
"order_id": 3,"digital_orders": [],"physical_orders": [
{
"title": "The Desert of the Tartars","total": 40
}
]
}
解决方法
您可以尝试
-
$group
byorder_id
并获得第一个customer_name
并获得数组中具有必填字段的所有订单 -
$project
以显示必填字段,将2个字段分别设置为digital_orders
和physical_orders
以过滤来自订单数组的实物订单,db.collection.aggregate([ { $group: { _id: "$order_id",customer_name: { $first: "$customer_name" },orders: { $push: { title: "$title",price: "$price",order_type: "$order_type" } } } },{ $project: { _id: 0,order_id: "$_id",customer_name: 1,digital_orders: { $filter: { input: "$orders",cond: { $eq: ["$$this.order_type","digital"] } } },physical_orders: { $filter: { input: "$orders","physical_delivery"] } } } } } ])
用于过滤来自订单数组的数字订单
{{1}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。