我有一些学生,每个学生在每月的不同日子里被分配做家务。
例如:
{ name: 'Josh', choredays: [2, 5, 16, 20, 28]},
{ name: 'Will', choredays: [5, 15, 18, 21, 22]}
给定一个数字,我希望第二天得到每个学生必须做家务的输出。
例如,给定14
,我想得到
Josh 16
Will 15
如何在 Mongo Aggregation 中表达这一点?
最佳答案
您可以尝试以下聚合
您需要使用$filter
聚合运算符消除了较少的输入值。然后使用 $slice
这消除了较大的值。
db.collection.aggregate([
{ "$addFields": {
"items": {
"$filter": {
"input": "$choredays",
"as": "chore",
"cond": { "$gte": [ "$$chore", 14 ] }
}
}
}},
{ "$addFields": { "items": { "$slice": [ "$items", 0, 1 ] }}},
{ "$unwind": "$items" },
{ "$project": { "items": 1, "name": 1 }}
])
将给出以下输出
[
{
"items": 16,
"name": "Josh"
},
{
"items": 15,
"name": "Will"
}
]
您可以查看here
关于arrays - 在 mongodb 数组中查找最接近的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799738/