David
David

Reputation: 560

MongoDB: Remove all array entries except the last X entries

Node.JS MongoDB Driver is used. The database entries look like that:

{
    _id: ObjectId("224444202654a21928801814"),
    category: "Test", 
    entries: [
        {
            _id: ObjectId("324444202dd4a21328802214"),
            username: "Tester",
        },
        {
            _id: ObjectId("324444232dd4a21328802215"),
            username: "Tester2",
        }
        [many more...]
    ]
}

There are thousands of objects in the entries array. The last array entries are the newest ones. Now all objects should be deleted inside the entries array except the last 50 entries. Is there a possibility to achieve that with one update/remove call? Maybe with the $slice operator?

Upvotes: 1

Views: 1130

Answers (1)

Anand Jayabalan
Anand Jayabalan

Reputation: 12904

It's not possible to achieve what you want with the $slice operator. I think using the javascript slice operator within cursor forEach() is your best bet. Try this out:

db.foo.find({}).forEach( function(doc) { 
    db.foo.update(
        {_id:doc._id}, 
        {$set:{entries:doc.entries.slice(doc.entries.length - 50)}}
    ) 
})

Note: The above command would run fine in the Mongo Shell.

Upvotes: 1

Related Questions