Cosmos query to find unique count

I have the following documents in Cosmos where I want to get distinct count of stockNumber with associated lineItems with Waiting-Reconciliation status.

Data:

Doc-1:

{
    "stockNumber": "123",
    "lineItems": [
        {
            "itemState": "Reconciled"
        },
        {
           "itemState": "Waiting-Reconciliation"
        },
        {
            "itemState": "Waiting-Reconciliation"
        }
    ]
}

Doc-2:

{
    "stockNumber": "234",
    "lineItems": [
        {
            "itemState": "Waiting-Reconciliation"
        }
    ]
}

Doc-3:

{
    "stockNumber": "345",
    "lineItems": [
        {
            "itemState": "Reconciled"
        },
        {
            "itemState": "Reconciled"
        }
    ]
}

Desired Output:
Here "123" and "234" has itemState with Waiting-Reconciliation so both of them are qualified.

[
    {
        "stockCount": 2,
        "lineItemCount": 3
    }
]

Queries:

When I run this,

SELECT COUNT(DISTINCT c.stockNumber) AS stockCount, 
COUNT(c.lineItems) AS lineItemCount 
FROM c JOIN l IN c.lineItems 
WHERE l.itemState="Waiting-Reconciliation"

then I get this error.

{"code":"BadRequest","message":"One of the input values is invalid.\r\nActivityId: 1b7d21f5-2d83-4e9a-834c-26729f5bad1d, Windows/10.0.20348 cosmos-netstandard-sdk/3.18.0"}

Now, If I just remove DISTINCT then it returns 3 for both, which I don’t want. What am I missing here?

SELECT 
count(c.stockNumber) AS stockCount, 
count(c.lineItems) AS lineItemCount 
FROM c JOIN l IN c.lineItems 
WHERE l.itemState="Waiting-Reconciliation"

Note:
This runs successfully, but when I try to get the count, it throws the above-mentioned error.

SELECT
  DISTINCT c.stockNumber AS stockCount,
  c.lineItems AS lineItemCount
FROM c JOIN l 
IN c.lineItems 
WHERE l.itemState="Waiting-Reconciliation"

Basically, I want to combine these two queries in one. Or at least, combine their results.

SELECT COUNT(c) AS stockCount 
FROM c WHERE ARRAY_LENGTH(c.lineItems) > 0 
AND EXISTS (SELECT VALUE l FROM l IN c.lineItems WHERE STRINGEQUALS(l.itemState, 'Waiting-Reconciliation', true))

Result:

[
    {
        "stockCount": 2
    }
]
SELECT
  COUNT(c) AS lineItemCount
FROM c
  JOIN l IN c.lineItems 
WHERE l.itemState="Waiting-Reconciliation"

Result:

[
    {
        "lineItemCount": 3
    }
]

Leave a Comment