在mongodb项目聚合中有条件地包含一个字段(_id或其他字段)? [英] Conditionally include a field (_id or other) in mongodb project aggregation?

查看:606
本文介绍了在mongodb项目聚合中有条件地包含一个字段(_id或其他字段)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有$ project阶段的mongodb聚合管道,仅在满足条件的情况下,我才想包括某些字段.具体来说,我想在一种情况下排除_id,而在另一种情况下包含第二个字段"second_id".

I've got a mongodb aggregation pipeline with a $project stage and I'd like to include certain fields only if conditions are met. Specifically, I'd like to exclude the _id in one condition and include a second field 'second_id' in the other condition.

我知道尚无法从mongodb $ project中排除字段,但是有条件地包括它们吗?

I know that it's not possible (yet) to exclude fields from a mongodb $project, but is it possible to conditionally include them?

是否可以有条件地排除_id字段?它接受0或1,但是如果我想基于if语句确定0或1,该怎么办.怎么办?

Is there a way to conditionally exclude the _id field? It accepts a 0 or 1, but what if I want to determine that 0 or 1 based on an if statement. How would this be done?

_id的伪代码:

$project: { _id: { $ifNull: [ "$user_id", 0 ] } }

此方法的主要用途是将doc.user_id用作结果_id,或者如果该user_id为null,则允许mongodb创建一个新的自动增量_id.

The main use of this would be to use the doc.user_id as the result _id, or allow mongodb to create a new autoincrement _id if that user_id is null.

推荐答案

目前在$ project阶段尚无此方法,但是您可以使用$ redact阶段有条件地删除该字段(即您设置了就像您在示例中所做的那样,将值设置为0.

There isn't a way currently to do this within the $project stage, but you can use the $redact stage to remove the field conditionally (i.e. you set the value to 0 like you are doing in your example.

db.collection.aggregate(
  ... matching and stuff ...
  {$project: { _id: { $ifNull: [ "$user_id", 0 ] } }},
  {$redact: {
  {$cond: {
    if: { $eq: [ "$user_id", 0 ] },
    then: '$$PRUNE',
    else: '$$DESCEND'
  }}
}

这篇关于在mongodb项目聚合中有条件地包含一个字段(_id或其他字段)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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