【发布时间】:2015-03-25 01:06:05
【问题描述】:
我想从 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 时出现。
如何实现?
谢谢!
【问题讨论】:
标签: node.js mongodb mongoose aggregation-framework