【发布时间】:2020-06-19 19:19:38
【问题描述】:
我的收藏样本:
[
{
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
age: 55,
location: "texas",
joining_date: 2019-01-01T15:24:15.068+00:00
},
{
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
age: 45,
location: "texas",
joining_date: 2019-01-01T15:24:15.068+00:00
},
{
_id: "bmasndvhjbca",
name: "stuart",
occupation: "lab assistant",
age: 25,
location: "texas",
joining_date: 2019-01-02T20:25:16.068+00:00
},
{
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
age: 69,
location: "texas"
}
]
哪个文档有 joining_date 列需要通过检查日期来添加一个值增加的字段,例如joining_date_count:1
如果日期相同,例如 mark 和 lucas 两种情况。 count 应将其视为不同的值并增加计数。
预期输出:
[
{
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
age: 55,
location: "texas",
joining_date: 2019-01-01T15:24:15.068+00:00,
joining_date_count:1
},
{
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
age: 45,
location: "texas",
joining_date: 2019-01-01T15:24:15.068+00:00,
joining_date_count:2
},
{
_id: "bmasndvhjbca",
name: "stuart",
occupation: "lab assistant",
age: 25,
location: "texas",
joining_date: 2019-01-02T20:25:16.068+00:00,
joining_date_count:3
},
{
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
age: 69,
location: "texas"
}
]
【问题讨论】:
-
您的收藏有多大?因为如果文档不是基于
joining_date从高(最新)到低(旧)保存的,那么我们需要实现$sort,这在大型数据集上可能会出现问题.. -
集合很小,我们可以对其使用排序。
标签: mongodb mongodb-query aggregation-framework