Mongo. Query documents with an array whose childs ALL have to match a query
Mongo. Query documents with an array whose childs ALL have to match a query
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.
Here's what I have:
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?
1 Answer
1
You can use $map to apply your condition for each shipment
and then use $allElementsTrue inside $expr to check if all those elements match:
shipment
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") ]
]
])
@brechtvhb included that check in my answer
– mickl
Aug 28 at 20:15
Your updated query does not seem to work :(. It returns nothing
– brechtvhb
Aug 28 at 20:17
@brechtvhb I believe it still works, you can verify here: mongoplayground.net/p/D_wcy4dxKjy
– mickl
Aug 28 at 20:45
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thank you that seems to work. I only needed to add a check to be sure the array was not empty. I added this statement to my match stage (in an AND): "shipments.0" : $exists: true
– brechtvhb
Aug 28 at 20:12