I have following docs
{
"_id": "products:info",
"_rev": "3-47add0ce8ecbcb2c4c7dfefae83c02cd",
"created": "01-26-2022",
"products": [
{
"brand": "MSI",
"title": "Summit e16",
"sku": "1000121"
},
{
"brand": "MSI",
"title": "Summit e13",
"sku": "1000120"
}
]
}
I wanted to sort products array by sku property in desc order and get first product sku.
I tried following so far.
Index
{
"type": "json",
"partitioned": true,
"def": {
"fields": [
{
"products[].sku": "asc"
}
]
}
}
Query
{
"selector": {
"products": {
"$elemMatch": {
"sku": {
"$ne": null
}
}
}
},
"fields": [
"_id",
"products.0.sku"
],
"sort": [
{
"products.sku": "desc"
}
]
}
Throwing error
Error running query. Reason: (no_usable_index) No global index exists for this sort, try indexing by the sort fields.
Tried following as well
{"products.sku": "desc"}
{"products.[].sku": "desc"}
As commented
So the desired outcome cannot be achieved with a
_findselector. Since that is so, I will offer a suggestion and an alternative.First, putting all products into a single file seems like a bad idea - denormalization gone wild? If this is a real world application do note the
$elemMatchis an in-memory operation and may result in poor outcomes for a very large product list.The solution is easily achieved with a view. Consider this
mapfunctionGiven the example document from the OP the view index would look like this
There may be other requirements, but this view covers a lot
valuefield removes the need to load the actual document for specific information_countprovides some nice information with regards to (non)null skus for freeIn the snippet below the products list is
and the resulting view index looks like this
The default state of the snippet when executing the view solves the OP requirement.
Disclaimer
I would normalize products by moving each product into its own document.