我在 MongoDB 中有一个包含约 300 万个文档的数据库,每个文档的大小约为 30KB。 我在大多数文档中都有一个名为“商店”的字段,它是一个对象数组。 在其他文档中,该字段不存在。 该数组中的每个对象都与商店的数据有关。
结构体和字段如下-
shops: [
{
'name': 'Shop1',
'total_count': 20,
'positive_sentiment_count': 5,
'negative_sentiment_count': 1,
'neutral_sentiment_count': 3,
.
.
.
.
.
},
{
'name': 'Shop2',
'total_count': 15,
'positive_sentiment_count': 10,
'negative_sentiment_count': 3,
'neutral_sentiment_count': 2,
.
.
.
.
.
},
.
.
.
]
在“商店”所在的同一级别,我有一个名为“date”的时间戳日期字段,在对数据库进行的每个查询中都需要该字段。
我有shops.name_1_date_1和date_1_shop.name_1的索引 目标是给定商店名称和日期范围,我想仅根据日期范围获取所有匹配文档中该商店的计数总和。 这包括获取商店对象内所有字段的计数总和。 类似于这些字段 - 'total_count'、'positive_sentiment_count'、'negative_sentiment_count'、'neutral_sentiment_count
还有 6 个计数字段需要在匹配文档中求和。
我有一个管道可以做到这一点,我什至尝试在 Python 中投影“商店”对象信息和过程,但无论哪种方式,延迟都相当高。
对于 50000 个文档,运行大约需要 20 秒。 我们可以假设以下参数 -
独特店铺名称最大数量~400 所有计数字段都是整数。 数据库中“shops”字段的平均长度约为 20 每个“shops”对象内的字段数量为 10 每个商店对象都属于一个唯一的商店名称。
以下是我当前的管道 -
我尝试在对象字段和数组字段上构建索引,但我注意到覆盖查询不适用于这些数据类型。有这种情况吗?
db.collection.aggregate([
{ $match: { date: { $gte: <startDate>, $lte: <endDate> }, "shops.name": <shopName> } }, // Filter by date and shop name
{ $unwind: "$shops" }, // Unwind the shops array
{ $match: { "shops.name": <shopName> } }, // Match specific shop name after unwind
{
$group: {
_id: null,
total_count: { $sum: "$shops.total_count" },
positive_sentiment_count: { $sum: "$shops.positive_sentiment_count" },
negative_sentiment_count: { $sum: "$shops.negative_sentiment_count" },
neutral_sentiment_count: { $sum: "$shops.neutral_sentiment_count" }
// Add the other count fields as well
}
}
]);