MongoDB $push until max array size

Overview

We have a Mongo database collecting time series data from multiple different stream channels. This data is stored using a paging pattern where each page document holds a subset of the overall timeline (currently 3600 points per page).

For example, we may have 10,000 data points divided into 3 pages with capacities: 3600, 3600, 2800 respectfully.

Below is our current update operation, it pushes a new point to the points array within a collection containing less than 3600 datapoints (defined by count).

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>db.stream_pages.updateOne(
{
"stream_id": ObjectId("635046f885b5ab956ba279a6"),
"group_id": ObjectId("6277597d7558ec17694ae0f8"),
"count": {
"$lt": 3600
}
},
{
"$push": {
"points": 100
},
"$inc": {
"count": 1
},
"$set": {
"end": Date()
},
"$setOnInsert": {
"stream_id": ObjectId("635046f885b5ab956ba279a6"),
"begin": Date(),
"group_id": ObjectId("6277597d7558ec17694ae0f8")
}
},
upsert: true
)
</code>
<code>db.stream_pages.updateOne( { "stream_id": ObjectId("635046f885b5ab956ba279a6"), "group_id": ObjectId("6277597d7558ec17694ae0f8"), "count": { "$lt": 3600 } }, { "$push": { "points": 100 }, "$inc": { "count": 1 }, "$set": { "end": Date() }, "$setOnInsert": { "stream_id": ObjectId("635046f885b5ab956ba279a6"), "begin": Date(), "group_id": ObjectId("6277597d7558ec17694ae0f8") } }, upsert: true ) </code>
db.stream_pages.updateOne(
    {
        "stream_id": ObjectId("635046f885b5ab956ba279a6"),
        "group_id": ObjectId("6277597d7558ec17694ae0f8"),
        "count": {
            "$lt": 3600
        }
    },
    {
        "$push": {
            "points": 100
        },
        "$inc": {
            "count": 1
        },
        "$set": {
            "end": Date()
        },
        "$setOnInsert": {
            "stream_id": ObjectId("635046f885b5ab956ba279a6"),
            "begin": Date(),
            "group_id": ObjectId("6277597d7558ec17694ae0f8")
        }
    },
    upsert: true
)

Problem Statement

We are starting to get a higher influx of data causing a significant amount of $push operations on updates. Currently, each incoming datapoint requires a $push into the latest page document. The latest document is defined as the only document containing less than 3600 points (custom indexes are used to optimize this lookup).

We would prefer to push N items into existing pages similarly like so:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>db.stream_pages.updateOne(
{
"stream_id": stream_id,
"group_id": group_id,
"count": {
"$lt": 3600
}
},
{
"$push": {
"points": {
"$each": [ 100, 100, 101, 20 ],
}
},
"$inc": {
"count": N # current length of array passed
},
"$set": {
"end": Date()
},
"$setOnInsert": {
"stream_id": stream_id,
"begin": Date(),
"group_id": group_id
},
},
upsert: true
)
</code>
<code>db.stream_pages.updateOne( { "stream_id": stream_id, "group_id": group_id, "count": { "$lt": 3600 } }, { "$push": { "points": { "$each": [ 100, 100, 101, 20 ], } }, "$inc": { "count": N # current length of array passed }, "$set": { "end": Date() }, "$setOnInsert": { "stream_id": stream_id, "begin": Date(), "group_id": group_id }, }, upsert: true ) </code>
db.stream_pages.updateOne(
    {
        "stream_id": stream_id,
        "group_id": group_id,
        "count": {
            "$lt": 3600
        }
    },
    {
        "$push": {
            "points": {
                "$each": [ 100, 100, 101, 20 ],
            }
        },
        "$inc": {
            "count": N # current length of array passed
        },
        "$set": {
            "end": Date()
        },
        "$setOnInsert": {
            "stream_id": stream_id,
            "begin": Date(),
            "group_id": group_id
        },
    },
    upsert: true
)

While this operation works, it does not respect the cap of 3600 datapoints we put on each page, causing pages to grow in excess of 3600 points. The ideal update operation would handle two cases: point capacity is respected and overflow points are upserted into a new document.

Does Mongo have a method to find and then use the queried document as input conditionals for the update? Worst case we do a query before this insertion and only push a calculated amount of points to the array, this is not atomic however which can cause issues down the line.

3

There is no option to do a single update with the current structure, while it sounds like you could benefit from a schema redesign I understand the difficulty involved in such a migration so I let’s see what are our options given the current state of things:

  1. I’ll start with what I think is the best approach, just executing multiple (~2) updates until all requirements are met.

Here is how the code would look like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const newPoints = [100, 100, 101, 20];
let remaining = newPoints.length;
while (remaining > 0) {
const prev = await db.stream_pages.findOneAndUpdate(
{
"stream_id": stream_id,
"group_id": group_id,
"count": {
"$lt": 3600
}
},
[
{
"$set": {
"points": {"$concatArrays": [{"$ifNull": ["$points", []]}, {"$slice": [newPoints, {"$subtract": [3600, {"$ifNull": ["$count", 0]}]}]}]},
"count": {"$sum": [{"$ifNull": ["$count", 0]}, {"$max": [{"$subtract": [3600, {"$ifNull": ["$count", 0]}]}, {$size: newPoints}]}]},
"end": Date(),
"begin": {"$ifNull": ["$begin", Date()]},
"group_id": {"$ifNull": ["$group_id", group_id]},
"stream_id": {"$ifNull": ["$stream_id", stream_id]},
}
}
],
{
upsert: true
}
);
remanining = remanining - (3600 - (prev.value ? prev.value.count : newPoints.length))
}
</code>
<code>const newPoints = [100, 100, 101, 20]; let remaining = newPoints.length; while (remaining > 0) { const prev = await db.stream_pages.findOneAndUpdate( { "stream_id": stream_id, "group_id": group_id, "count": { "$lt": 3600 } }, [ { "$set": { "points": {"$concatArrays": [{"$ifNull": ["$points", []]}, {"$slice": [newPoints, {"$subtract": [3600, {"$ifNull": ["$count", 0]}]}]}]}, "count": {"$sum": [{"$ifNull": ["$count", 0]}, {"$max": [{"$subtract": [3600, {"$ifNull": ["$count", 0]}]}, {$size: newPoints}]}]}, "end": Date(), "begin": {"$ifNull": ["$begin", Date()]}, "group_id": {"$ifNull": ["$group_id", group_id]}, "stream_id": {"$ifNull": ["$stream_id", stream_id]}, } } ], { upsert: true } ); remanining = remanining - (3600 - (prev.value ? prev.value.count : newPoints.length)) } </code>
const newPoints = [100, 100, 101, 20];
let remaining = newPoints.length;
while (remaining > 0) {
    const prev = await db.stream_pages.findOneAndUpdate(
        {
            "stream_id": stream_id,
            "group_id": group_id,
            "count": {
                "$lt": 3600
            }
        },
        [
            {
                "$set": {
                    "points": {"$concatArrays": [{"$ifNull": ["$points", []]}, {"$slice": [newPoints, {"$subtract": [3600, {"$ifNull": ["$count", 0]}]}]}]},
                    "count": {"$sum": [{"$ifNull": ["$count", 0]}, {"$max": [{"$subtract": [3600, {"$ifNull": ["$count", 0]}]}, {$size: newPoints}]}]},
                    "end": Date(),
                    "begin": {"$ifNull": ["$begin", Date()]},
                    "group_id": {"$ifNull": ["$group_id", group_id]},
                    "stream_id": {"$ifNull": ["$stream_id", stream_id]},
                }
            }
        ],
        {
            upsert: true
        }
    );

    remanining = remanining - (3600 - (prev.value ? prev.value.count : newPoints.length))
}

The idea is to calculate the remaining size based on the update result, because each update is atomic this code can run in multiple process in parallel with no issues.

The only edge case I did not handle is if the input “newPoints” size is over 3600, if this is possible you’ll have to add it in yourself.

The second options is slightly cleaner code, it is using the aggregation pipeline with the $merge stage, the issue with this approach and also the reason why I don’t recommend it as it’s not atomic like an update should be.
Therefor this should only be used if only a single process is handling these updates, even then you’ll have to add additional logic in code to make sure only 1 update is executed at a time, or to use transactions to ensure that.
Another edge case issue is that it requires at least one document in the collection to already exist.

Either way not very optimal, If you want me to provide syntax for it then i’ll be glad to but as I mentioned I recommend against this approach.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật