蒙哥使用其所有子项都必须与查询匹配的数组来查询文档 [英] Mongo. Query documents with an array whose childs ALL have to match a query

查看:48
本文介绍了蒙哥使用其所有子项都必须与查询匹配的数组来查询文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mongo聚合框架编写查询.我要实现的是选择一个月前所有货物已交付的订单.

I am trying to write a query by using the mongo aggregation framework. What I want to achive is to select the orders where ALL shipments have been delivered more than a month ago.

目前,我可以选择至少一个月前已交付至少一件"的订单.

currently I am able to select the orders where AT LEAST ONE shipment has been delivered more than a month ago.

这就是我所拥有的:

db['shop.orders'].aggregate(
{
  $match: { 
    shipments: { $elemMatch: { status: "Delivered", deliveredAt: {"$lte":new Date("2018-07-28")}} }
     }
})

我该如何更改查询以仅选择一个多月前已交付所有货物的订单?

How do I have to alter my query to only select the orders where ALL shipments have been delivered more than a month ago?

推荐答案

您可以使用 $ map 为每个货件应用条件,然后使用 $ allElementsTrue "nofollow noreferrer"> $ expr 检查所有这些元素是否匹配:

You can use $map to apply your condition for each shipment and then use $allElementsTrue inside $expr to check if all those elements match:

db.shop_orders.aggregate([
    {
        $match: { shipments: { $exists: true, $ne: [] } }
    },
    {
        $match: {
            $expr: {
                $allElementsTrue: {
                    $map: {
                        input: "$shipments",
                        as: "shipment",
                        in: {
                            $and: [
                                { $eq: [ "$$shipment.status", "Delivered" ] },
                                { $lte: [ "$$shipment.deliveredAt", new Date("2018-07-28") ] }
                            ]
                        }
                    }
                } 
            }
        }
    }
])

这篇关于蒙哥使用其所有子项都必须与查询匹配的数组来查询文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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