1

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?

1
  • I am able to get entries which are not in last 50 records. Now finding the way to delete them. Commented Apr 3, 2014 at 14:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, I will use this solution for the moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.