mongodb-使用条件的$ addtoset
在小组聚合中,我只是尝试将名称添加到20岁的情况下:
假设我有以下两个文档:
_id: ...
timestamp: ...
name: Max
age: 20
_id: ...
timestamp: ...
name: Brian
age: 21
现在,我正在尝试对这些文档进行分组,并在$ $ group 我正在尝试将所有20岁儿童的名称添加到一个集合中:
{
$group: {
_id: {
bins: {
$dateTrunc: {
date: '$timestamp',
unit: 'week',
binSize: 1
}
}
},
'NamesWithAge20': {
$addToSet: '$name'
}
}
}
我只对'namesWithage20'set感兴趣。在此代码中,现在将Max和Brian都添加到集合中,但是我想引入一个条件,该条件仅在年龄20岁时添加名称。在这个阶段,这是可能的吗?
In a group aggregation, I'm simply trying to add names to a set if the age is 20:
Let's say I have the following two documents:
_id: ...
timestamp: ...
name: Max
age: 20
_id: ...
timestamp: ...
name: Brian
age: 21
Now I'm trying to group these and in the $group
and I'm trying to add the name of all 20 year-olds to a set:
{
$group: {
_id: {
bins: {
$dateTrunc: {
date: '$timestamp',
unit: 'week',
binSize: 1
}
}
},
'NamesWithAge20': {
$addToSet: '$name'
}
}
}
I'm only interested in the 'NamesWithAge20' set. In this code right now both Max and Brian are added to the set, but I want to introduce a condition that only adds the name if the age is 20. Is that possible in this stage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以,使用
$ cond
和$$ remove
。$$删除
示例mongo playground
如果您只想用
age>年龄查询文档:20
,,建议添加$ MATD
阶段以在$ group
阶段之前过滤文档。示例mongo playground(
$ filter
)Yes you can, work with
$cond
and with$$REMOVE
.$$REMOVE
Sample Mongo Playground
If you just want to query the document with
age: 20
, would suggest adding$match
stage to filter the documents before$group
stage.Sample Mongo Playground (
$filter
)