mongodb聚合与$ project有条件地排除字段 [英] mongodb aggregation with $project to conditionally exclude a field

查看:1071
本文介绍了mongodb聚合与$ project有条件地排除字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从mongo db aggergtion管道中排除某个字段,在阅读文档后,我认为我需要指定1或0来保留该字段(或不保留该字段)(参见解决方案

从mongoDB 3.6开始,您可以使用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有条件地排除字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆