我正在尝试使用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") ] } ] } } } } } } ])更多推荐
蒙哥使用其所有子项都必须与查询匹配的数组来查询文档
发布评论