MongoDB -- 在 .find() 中设置条件语句 [英] MongoDB -- Setting a conditional statement in .find()

查看:70
本文介绍了MongoDB -- 在 .find() 中设置条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于聚合,$cond 可用于形成 if 语句.我想知道 .find() 是否有类似的功能

for aggregate, $cond can be used to form an if-statement. I'm wonder if there's a similar function for .find()

当我尝试在 find() 中使用 $cond 时,我得到

When I tried using $cond in find(), I get

"unknown top level operator: $cond"

我正在尝试执行以下操作(在伪代码中):

I'm trying to do the following (in pseudo code):

if condition is True:
    set filter for find to thing_1
else:
    set filter for find to thing_2

推荐答案

如果您使用的是 Mongo 3.6 或更高版本,您可以尝试使用 $expr 运算符.这将允许您使用 $cond.

If you are on Mongo 3.6 or greater, you could try using the $expr operator. Which would then allow you to use $cond.

$expr 允许在查询语言中使用聚合表达式.

$expr Allows the use of aggregation expressions within the query language.

他们的例子可以在这里

db.supplies.find( {
    $expr: {
       $lt:[ {
          $cond: {
             if: { $gte: ["$qty", 100] },
             then: { $divide: ["$price", 2] },
             else: { $divide: ["$price", 4] }
           }
       },
       5 ] }
} )

这篇关于MongoDB -- 在 .find() 中设置条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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