mongodb 与 $project 聚合以有条件地排除字段
mongodb aggregation with $project to conditionally exclude a field
我想从 mongo db aggergtion 管道中排除一个字段,在阅读文档后,我想我需要指定 1 或 0 来保留或不保留该字段(参见 http://docs.mongodb.org/manual/reference/operator/aggregation/project/)
所以我尝试了以下(使用 node.js mongoose,但语法与普通 mongo 完全相同):
aggregate.match({ date: { $gte : today } });
aggregate.sort('-date');
aggregate.group({
_id: '$name',
date: { $first: '$date' },
user: { $first: '$user' },
app: { $first: '$app' }
});
aggregate.project({
_id: 1,
last: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$date', 0 ] },
user: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$user', 0 ] },
app: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$app', 0 ] }
});
但是这样做,我以这样的文档结尾:
[
{
_id: 'devices',
user: 0,
app: 0,
last: 0
},
{
_id: 'undo',
user: 'test',
app: 'truc',
last: Mon Jan 26 2015 16:21:53 GMT+0100 (CET)
}
]
我希望 user
、app
和 date
仅在 _id
为 undo
时出现。
如何实现?
谢谢!
我认为这还不可能。
尝试排除 non-_id 字段时来自 shell 的错误消息:
The top-level _id field is the only field currently supported for exclusion
从 mongoDB 3.6 开始,您可以使用 the REMOVE variable 有条件地排除字段。
在您的特定情况下,项目阶段应如下所示:
aggregate.project({
_id: 1,
last: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$date', '$$REMOVE' ] },
user: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$user', '$$REMOVE' ] },
app: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$app', '$$REMOVE' ] }
});
我想从 mongo db aggergtion 管道中排除一个字段,在阅读文档后,我想我需要指定 1 或 0 来保留或不保留该字段(参见 http://docs.mongodb.org/manual/reference/operator/aggregation/project/)
所以我尝试了以下(使用 node.js mongoose,但语法与普通 mongo 完全相同):
aggregate.match({ date: { $gte : today } });
aggregate.sort('-date');
aggregate.group({
_id: '$name',
date: { $first: '$date' },
user: { $first: '$user' },
app: { $first: '$app' }
});
aggregate.project({
_id: 1,
last: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$date', 0 ] },
user: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$user', 0 ] },
app: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$app', 0 ] }
});
但是这样做,我以这样的文档结尾:
[
{
_id: 'devices',
user: 0,
app: 0,
last: 0
},
{
_id: 'undo',
user: 'test',
app: 'truc',
last: Mon Jan 26 2015 16:21:53 GMT+0100 (CET)
}
]
我希望 user
、app
和 date
仅在 _id
为 undo
时出现。
如何实现?
谢谢!
我认为这还不可能。
尝试排除 non-_id 字段时来自 shell 的错误消息:
The top-level _id field is the only field currently supported for exclusion
从 mongoDB 3.6 开始,您可以使用 the REMOVE variable 有条件地排除字段。
在您的特定情况下,项目阶段应如下所示:
aggregate.project({
_id: 1,
last: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$date', '$$REMOVE' ] },
user: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$user', '$$REMOVE' ] },
app: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$app', '$$REMOVE' ] }
});