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") ]
]






])





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






@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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế