mongodb - 聚合 $group 以了解集合中的上一个和下一个文档
问题描述
从这个 mongodb 操场示例: https ://mongoplayground.net/p/2yip2tRycYd
数据:
[
{
text: "bond",
createdAt: ISODate("2021-07-20T07:02:39.299+00:00"),
category: "films"
},
{
text: "monty python",
createdAt: ISODate("2021-07-21T07:06:39.299+00:00"),
category: "films"
},
{
text: "blow",
createdAt: ISODate("2021-07-21T07:12:39.299+00:00"),
category: "films"
},
{
text: "cake",
createdAt: ISODate("2021-07-24T10:01:39.299+00:00"),
category: "food"
},
{
text: "shoes",
createdAt: ISODate("2021-07-24T11:02:39.299+00:00"),
category: "clothes"
},
{
text: "bread",
createdAt: ISODate("2021-07-24T12:02:39.299+00:00"),
category: "food"
},
{
text: "bmw",
createdAt: ISODate("2021-07-24T12:05:39.299+00:00"),
category: "cars"
},
{
text: "tree",
createdAt: ISODate("2021-07-24T12:05:39.299+00:00"),
category: "world"
},
{
text: "fork",
createdAt: ISODate("2021-07-24T12:05:39.299+00:00"),
category: "kitchen"
},
]
查询
db.collection.aggregate([
{
$group: {
_id: {
day: {
$dayOfMonth: "$createdAt"
},
month: {
$month: "$createdAt"
},
year: {
$year: "$createdAt"
},
category: "$category"
},
count: {
$sum: 1
},
createdAt: {
"$addToSet": "$createdAt"
},
text: {
"$addToSet": "$text"
},
category: {
"$addToSet": "$category"
},
},
},
{
$sort: {
"createdAt": 1
}
},
{
$skip: 0
},
{
$limit: 5
},
])
结果
[
{
"_id": {
"category": "films",
"day": 20,
"month": 7,
"year": 2021
},
"category": [
"films"
],
"count": 1,
"createdAt": [
ISODate("2021-07-20T07:02:39.299Z")
],
"text": [
"bond"
]
},
{
"_id": {
"category": "films",
"day": 21,
"month": 7,
"year": 2021
},
"category": [
"films"
],
"count": 2,
"createdAt": [
ISODate("2021-07-21T07:06:39.299Z"),
ISODate("2021-07-21T07:12:39.299Z")
],
"text": [
"blow",
"monty python"
]
},
{
"_id": {
"category": "food",
"day": 24,
"month": 7,
"year": 2021
},
"category": [
"food"
],
"count": 2,
"createdAt": [
ISODate("2021-07-24T10:01:39.299Z"),
ISODate("2021-07-24T12:02:39.299Z")
],
"text": [
"bread",
"cake"
]
},
{
"_id": {
"category": "clothes",
"day": 24,
"month": 7,
"year": 2021
},
"category": [
"clothes"
],
"count": 1,
"createdAt": [
ISODate("2021-07-24T11:02:39.299Z")
],
"text": [
"shoes"
]
},
{
"_id": {
"category": "world",
"day": 24,
"month": 7,
"year": 2021
},
"category": [
"world"
],
"count": 1,
"createdAt": [
ISODate("2021-07-24T12:05:39.299Z")
],
"text": [
"tree"
]
}
]
结果如预期 - 我们将 2 部电影和 2 种食物组合在一起。
但是,是否有更多的配置可以注入到查询中,其中的项目介于或不在要分组的项目之间。
在上面的示例中,是否可以更改聚合以将所有第一部电影组合在一起(因为在集合中它们都彼此相邻),而不是将食物组合在一起,因为它们之间有衣服?
解决方案
推荐阅读
- amazon-web-services - 无法从实例本身访问 AWS nlb 目标组实例
- swift - 在不重新启动应用程序的情况下以编程方式更改应用程序语言
- eclipse - Spring Tools Suit 4 和 Spring roo
- php - 如何更改 Woocommerce 产品变体描述标签名称(管理端)
- c# - 手动列上的高级 DataGridView
- php - 如何在使用 LEFT JOIN 和 GROUP BY 时显示不同列的总值
- python - 如何在文本文件中查找一个单词并在 Python 的下一行中打印另一个单词
- javascript - 如何在本机反应中预加载音频文件?
- selenium - 如何将代理添加到 Scrapy 和 Selenium 脚本
- java - 改造在请求中发送base64图像