问题
I have the following result from a query, where count field is derived from an aggregate function
[
{
"count": 1,
"facilityName": "Hyundai Service Center"
},
{
"count": 2,
"facilityName": "Honda Service Center"
},
{
"count": 1,
"facilityName": "Kat Service Center"
}
]
I want to display only those facilityName where count >= 2.
How can we achieve this?
回答1:
I tried to implement your requirement with Stored procedure,please refer to my SP code:
function sample(idArray) {
var collection = getContext().getCollection();
var length = idArray.length;
var sqlQuery = {
"query": 'SELECT count(c.id) as cnt, f.facilityName from c join f in c.facilities '+
'where array_contains( @idArray,c.id,true) ' +
'AND c.entityType = "ServiceInformationFacility" group by f.facilityName',
"parameters": [
{"name": "@idArray", "value": idArray}
]
}
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
sqlQuery,
function (err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var returenArray = [];
for(var i=0;i<feed.length;i++){
if(feed[i].cnt==length)
returenArray.push(feed[i])
}
response.setBody(returenArray);
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
Input param:
["6ECF4568-CB0E-4E11-A5CD-1206638F9C39","2ECF4568-CB0E-4E11-A5CD-1206638F9C39"]
Get output:
UPDATES:
So,if your collection is partitioned,maybe stored procedure is not suitable for you because partition key is necessary for execution of SP.Please refer to my detailed explanations in this thread:Delete Documents from Cosmos using Query without Partition Key Specification
Actually, there is no complex logic in my above sp code.It just loop the result of the sql and try to find which object.count
equals the idArray.length
which means the object.facilityName exists cross all the documents.
So,you don't have to use SP, you can use any tiny piece of code to handle the logic I describe above.
来源:https://stackoverflow.com/questions/59817894/substitute-for-having-clause-in-cosmosdb