我必须检查布尔标志并根据其条件返回不同的数据结果。 例如我有一系列书籍及其价格,正常查询结果是价格匹配10,但是如果showAll标志为true,则需要返回所有记录。
let showAll=true;
result= await db.aggregate([{$match:{$or:[showAll,{$eq:{"price":10}}]}}])
问题是,mongo 在其逻辑运算符中不接受任何对象变量!
我最终遇到了这个错误:
$or/$and/$nor entries need to be full objects.
根据 mongodb 聚合中的 $or 运算符的描述和,似乎没问题。
https://www.mongodb.com/docs/manual/reference/operator/aggregation/or/
我可以通过使用 if 子句检查变量并执行不同的查询来解决问题,但再次重复同样的事情看起来很不稳定且令人失望!
为什么不根据以下条件生成查询,
let showAll = true;
result = showAll ?
await db.aggregate([]): // no stage will return all
await db.aggregate([{$match:{$or:[showAll,{$eq:{"price":10}}]}}]);