因此,我尝试了以下操作(使用node.js猫鼬,但语法与纯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时出现.如何实现?谢谢!解决方案从mongoDB 3.6开始,您可以使用 REMOVE变量以有条件地排除字段.在您的特定情况下,项目阶段应如下所示: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' ] }});I would like to exclude a field from a mongo db aggergtion pipeline, after reading the docs, I thought I needed to specify either 1 or 0 to keep the field or not (cf. http://docs.mongodb.org/manual/reference/operator/aggregation/project/)So I tried the following (using node.js mongoose, but the syntax is quite the same as plain 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 ] }});But doing that, I end with documents like this:[ { _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) }]I want the user, app and date to appear only when _id is undo.How to achieve it?Thanks! 解决方案 Starting in mongoDB 3.6, you can use the REMOVE variable to exclude fields conditionally.In your particular case, the project stage should look like this: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' ] }}); 这篇关于mongodb聚合与$ project有条件地排除字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 05:17