【问题标题】:Return all documents only if all matches conditions仅当所有匹配条件时才返回所有文档
【发布时间】:2020-02-12 21:45:04
【问题描述】:

寻找返回 true 或 false(或 false 或类似时为空数组)的查询的帮助我需要查询集合中的几个文档by id,并且仅在所有文档都与查询匹配时才返回 true,如果一个或多个文档不匹配,我需要返回一个错误值。

如果文档看起来像下面的检查值是真和假,我希望从查询中返回一个假/空数组值,但如果检查全部为真,我想要一个真或整个数组。

如果常规的find 更合适,我可以使用它。

我尝试过使用常规的 $match,但它只返回匹配的文档。

我现在很喜欢,但觉得可以用更好的方式来做?

 const coupons = await CouponModel.find({ id }, { checked: 1, _id: 0 });

 const everyCouponIsChecked = coupons.every(data => data.checked === true);

谢谢。

Sample data:

[ { _id: 5e43e7831bc81503efa54c61,
    id: 'foo',
    checked: true,
},
{ _id: 5e43e7831bc81503efa54c61,
    id: 'foo',
    checked: true,
},{ _id: 5e43e7831bc81503efa54c61,
    id: 'foo',
    checked: false,
}]


const result = await MyModel.aggregate([
    {
      $match: {
        id: 'foo',
        checked: true,

      },
    },

  ]);

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以使用带有 null _id 的 $group 阶段,然后使用 $allElementsTrue 运算符检查所有检查字段是否为真。

    这里是查询:

    db.collection.aggregate([
      {
        $group: {
          _id: null,
          docs: {
            $push: "$$ROOT"
          }
        }
      },
      {
        $addFields: {
          allTrue: {
            $allElementsTrue: "$docs.checked"
          }
        }
      },
      {
        $project: {
          result: {
            $cond: {
              if: {
                $eq: [
                  true,
                  "$allTrue"
                ]
              },
              then: "$docs",
              else: "$allTrue"
            }
          }
        }
      }
    ])
    

    如果任何选中的字段为假,结果将等于假,否则结果将等于文档数组。

    你可以测试一下here

    【讨论】:

      【解决方案2】:

      你可以用这样的查询来做

      const coupons = await CouponModel.find({ _id:id, checked:true });
      const everyCouponIsChecked = coupons.length > 0;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 2014-08-02
        • 2018-06-13
        • 2021-01-07
        相关资源
        最近更新 更多