sub文档数组中的couchbase n1ql查询总和



我在我的couchbase db

中具有以下文档模型
{
 type:"account"
 id : "123",
 transactions: [
   { 
      type : "credit",
      value : 100
   },
   { 
      type : "debit",
      value : 10
   }
 ]
}

如何查询所有帐户ID及其所有信用额度?

使用AS AS AS array函数https://docs.couchbase.com/server/6.0/n1ql/n1ql/n1ql-language-reference/arrayfun.html

SELECT d.id, 
   ARRAY_SUM(ARRAY v.`value` FOR v IN d.transactions WHEN v.type = "credit" END) AS s  
FROM default AS d
WHERE d.type = "account";

使用子查询表达式https://docs.couchbase.com/server/6.0/n1ql/n1ql/n1ql-language-reference/subqueries.html

 SELECT d.id, 
       (SELECT RAW SUM(d1.`value`) 
        FROM d.transactions AS d1
        WHERE d1.type = "credit")[0] AS s  
    FROM default AS d
    WHERE d.type = "account";

最新更新