我正在尝试过滤嵌入文档的数组,并在所有文档中获取count sum。
数据库中的数据结构。
{
name: String,
transactions: [{
type: String,
isValid: String
}]
}我还对类型和isValid字段使用了多个索引。
这是我的聚合。
await Collection.aggregate([
{ '$unwind': '$transactions' },
{ '$replaceRoot': { newRoot: '$transactions' } },
{ '$match': { '$and': [ { type: { '$eq': 'Anything' } },
{ '$or': [ { isValid: { '$eq': true } }, { isValid: { '$eq': null } } ] } ] } },
{ '$count': "count"}] 延迟约为15秒。
await Collection.aggregate([
{ '$count': "count"}]在聚合延迟中仅使用$count是相同的约15秒。不知道它是怎么工作的。
收款单计数超过1个。而获取嵌入式数组的计数和大约需要15秒。有没有人可以建议如何优化查询?
发布于 2019-08-05 17:46:57
尝试实现以下内容:
await Collection.aggregate([
{$group:{_id:null,count:{$sum:{$size:
{
$filter: {
input: "$transactions", as: "item",
cond:
{$and: [
{$eq: ["$$item.type", "Anything"]},
{ '$or': [ { "$eq":["$$item.isValid",true]},{ "$eq":["$$item.isValid",null]}] }
]}
}
}}}}}])https://stackoverflow.com/questions/57355617
复制相似问题