'findOneAndUpdate - document query > 1000

So I have a collection that has over 1million documents clearly, I don't need to search 1000 or more documents as it should only be updating the latest document.

const nowplayingData = {"type":"S",
                        "station": req.params.stationname, 
                        "song": data[1], 
                        "artist": data[0], 
                        "timeplay":npdate};

LNowPlaying.findOneAndUpdate( nowplayingData,
                             { $addToSet: { history: [uuid] } },
                             { upsert: true, sort: {_id:-1} }, 
                             function(err) {
                                            if (err) {
                                               console.log('ERROR when submitting round');
                                               console.log(err);
                                            }
                             });

I have added a sort on it, so that it is able to get the latest one first, but if the document is not in there and it's the first time the document is being added then the way the script is written will query all documents to find.

When really it only needs to look at the last say 100 documents or even better if timeplay is in the last 5 minutes.



Solution 1:[1]

You can do something like:

const nowplayingData = {
    "type":"S","station": req.params.stationname, "song": data[1], "artist": data[0], 
    "timeplay":{$gte: beforeFiveMin}};

But this will create a new document almost every time...so you will need to maintain it...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nimrod serok