dopplesoldner
dopplesoldner

Reputation: 9479

mongodb - concept of batches

I am using MongoDB with Node.js and have got stuck at a particular scenario.

Let's say I have a document store called samples which I use to collect some time stamps from the client machine.

I want to introduce the concept of batches

More precisely, I want to keep inserting into an existing document until the number of samples reaches a threshold, after which I would like to create a new document.

I can continue inserting and update number of samples to same document as follows

db.timestamps.update(
        {"guid": guid},
        {
            $inc: { samples: 1},
            $push: { timings: { clientTime: clientTime } }
        },
        { upsert: true }
    );

How can I add a check to stop inserting and create a new document once my sample count reaches say 300 for this example?

Thanks

Upvotes: 0

Views: 73

Answers (1)

Sammaye
Sammaye

Reputation: 43884

I am unsure if you can do this without two queries but you could try

db.col.update({
    guid:guid, samples: {$lt:300}
},
{
    $inc: { samples: 1},
    $push: { timings: { clientTime: clientTime } }
},
{
    upsert: true
})

That should insert a new document every 300 batches of the format:

{ "_id" : ObjectId("51e518ad8d065caa3b208661"), "guid" : 10, "samples" : 1, "timings" : [  {  "clientTime" : 1 } ] }

Upvotes: 1

Related Questions