Skip to content

Instantly share code, notes, and snippets.

@rcollette
Created September 6, 2019 04:16
Show Gist options
  • Save rcollette/48fa3a03343de0d9e8a7d38afabd8b29 to your computer and use it in GitHub Desktop.
Save rcollette/48fa3a03343de0d9e8a7d38afabd8b29 to your computer and use it in GitHub Desktop.
Example of a 3 level nested lookup and projection with MongoDb. This is effectively a paged search query.
db.someCollection.aggregate([
{
"$match":{
"$text":{
"$search":"boundary"
}
}
},
{
"$match":{
"$and":[
{
"isExcludedFromExternalSearch":{
"$ne":true
}
},
{
"$nor":[
{
"shopUrl":{
"$in":[
null,
""
]
},
"typeUrl":{
"$in":[
null,
""
]
}
}
]
},
{
"$or":[
{
"shopUrl":{
"$regex":"^.{1,}$",
"$options":"s"
}
},
{
"typeUrl":{
"$regex":"^.{1,}$",
"$options":"s"
}
}
]
},
{
"$or":[
{
},
{
"productFamilyId":{
"$in":[
]
}
}
]
}
]
}
},
{
"$addFields":{
"score":{
"$meta":"textScore"
}
}
},
{
"$sort":{
"Score":{
"$meta":"textScore"
}
}
},
{
"$skip":10
},
{
"$limit":11
},
{
"$lookup":{
"from":"products",
"localField":"productTypeId",
"foreignField":"productTypeId",
"as":"products"
}
},
{
"$lookup":{
"from":"deliveries",
"let":{
"products":"$products"
},
"pipeline":[
{
"$match":{
"$expr":{
"$and":[
{
"$in":[
"$productId",
"$$products.productId"
]
},
{
"$eq":[
"$deliveryType",
"Sample"
]
},
{
"$eq":[
"$availability",
"Released"
]
}
]
}
}
}
],
"as":"deliveries"
}
},
{
"$project":{
"description":"$externalProductTypeDesc",
"productTypeId":"$productTypeId",
"id":"$_id",
"name":"$name",
"productFamilyId":"$productFamilyId",
"isExternalUrl":{
"$or":[
{
"$eq":[
{
"$ifNull":[
"$shopUrl",
""
]
},
null
]
},
{
"$eq":[
{
"$ifNull":[
"$shopUrl",
""
]
},
""
]
}
]
},
"url":{
"$ifNull":[
"$shopUrl",
"$typeUrl"
]
},
"score":"$score",
"products":{
"$filter":{
"input":{
"$map":{
"input":"$products",
"as":"productForSelect",
"in":{
"productId":"$$productForSelect.productId",
"productInfo":"$$productForSelect.productInfo",
"productName":"$$productForSelect.productName",
"deliveries":{
"$map":{
"input":{
"$filter":{
"input":"$deliveries",
"as":"deliveryForWhere",
"cond":{
"$eq":[
"$$deliveryForWhere.productId",
"$$productForSelect.productId"
]
}
}
},
"as":"deliveryForSelect",
"in":{
"deliveryId":"$$deliveryForSelect.deliveryId",
"language":"$$deliveryForSelect.language",
"platform":"$$deliveryForSelect.platform",
"operatingSystem":"$$deliveryForSelect.operatingSystem",
"releaseInfo":"$$deliveryForSelect.releaseInfo"
}
}
}
}
}
},
"as":"productSearchResult",
"cond":{
"$and":[
{
"$ne":[
"$$productSearchResult.deliveries",
null
]
},
{
"$gt":[
{
"$size":"$$productSearchResult.deliveries"
},
0
]
}
]
}
}
},
"_id":0
}
}
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment