Erase multiple range records all at once in MongoDB

I have a challenge where I need to delete 50% of the records from my MongoDB collection, specifically targeting the oldest ones.

Here's the script I currently have:

var count = Twitter_tweets.find().count();
var limit = Math.round(count *.5);
var tweets = Twitter_tweets.find().sort({$natural:1}).limit(limit);

_.each(tweets,function(tweet){
    Twitter_tweets.delete({_id : tweet._id});
});

Since I'm using 'each' to iterate through and delete each record individually, I'm wondering if there is a way to delete all records at once with a single MongoDB instruction. Unfortunately, I haven't been able to find this information on Google. Is there a way to achieve this in MongoDB?

Answer №1

While I can't provide the exact Meteor code for this conversion, I can offer a potential strategy:

let totalTweets = Tweets_collection.find().count();
let deleteLimit = Math.floor(totalTweets * 0.5);
let middleTweet = Tweets_collection.find().sort({_id: 1}).skip(deleteLimit).limit(1).fetch()[0];

Tweets_collection.remove({_id: { $lt: middleTweet._id } });

The concept here is to fetch the document with the _id that falls in the middle of the collection and remove all documents with lower _id values relative to it. In general, the _id should be incrementally increasing unless there have been manipulations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Items vanish once collected from the cookie shop

In my $routeProvider definition, I included the access parameter for a route: $routeProvider.when('/tracks/:trackTitle/:mediaTitle', { templateUrl: 'views/track-detail.html', controller: 'MediaCtrl', access: acces ...

How can lazy loading of images be implemented in HTL code in AEM 6.5?

Looking to implement a Javascript for lazy loading images on a website in AEM 6.5. How should I proceed? I've set up a dialog for the component and added the necessary Javascript in clientlibs in AEM 6.5. What modifications do I need to make in the H ...

Instructions for adding a name to a string based on certain conditions

I am attempting to prepend a company name to a card number using the code provided. The challenge I am facing is incorporating the specific rules for each company as conditions for an if statement. Although I acknowledge that my current approach with the ...

How do you typically start off a state variable of type number when working with React?

Imagine having a state variable named amount and an input field that updates the variable as we type in it. The goal is to not display the initial value as 0. What would be the ideal way to initialize the state variable then? I attempted initializing it wi ...

Accessing files is not feasible with Firefox 17.0.1 extension

Ever since upgrading to Firefox 17.0.1, I have encountered an issue with PrivilegeManager no longer being supported. While some suggest that simply removing a line of code should fix the problem, it seems that is not the case for me. Every time I try to r ...

Adjust image source based on media query (CSS or JavaScript)

Is there a way to update the image src based on a media query with a maximum width of 515px? I'm considering using JavaScript, jQuery, or even AngularJS if there is an event equivalent to a CSS media query that can achieve this. I want to have differ ...

Submit form using jQuery after making an AJAX request with jQuery's $

I'm working on the following code: $.get(link, function(data, status) { document.getElementById("test").value = data; }); $('#formtest').submit(); Everything works fine in Firefox, but in Google Chrome the submit is done before t ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

Using jQuery to Extract HTML Content from a JSON Object

I'm completely lost on what I'm doing incorrectly, but the JSON string I have looks like this: jsonp443489({"content":"<!DOCTYPE html><html><head><title>Title</title></head><body><p>Hello World< ...

Creating a form in NextJS to securely transfer user input data to MongoDB

Being new to JavaScript, I have a basic understanding and some lack of experience, but I am eager to learn more. Recently, I embarked on a project using NextJS, an efficient framework that integrates with ReactJS. My current challenge lies in creating a si ...

What could be causing my CSS navigation toggle button to malfunction?

My attempt at creating a toggle button for tablets and phones seems to be failing. Despite the javascript class being triggered when I click the toggle button, it is not functioning as expected... https://i.stack.imgur.com/j5BN8.png https://i.stack.imgur. ...

Having trouble loading JSON data into HTML using jQuery

I'm struggling to create a basic menu using data from a JSON file. I've been attempting to figure out the correct logic for days now, but I seem to have hit a dead end: Here's the approach I've taken: $.ajax({ url: 'data ...

Removing the initial 0 from the input

I have a form input field that I want to format using jQuery 1.7.2 <input style="text-align:right;" type="text" name="DiversionCalc_Diversion_Rate" id="calc_dr" value="0.25%" /> My goal is to adjust the formatting when the input field loses focus. ...

Is it possible for me to pass a reference to a specific object's instance function?

Can JavaScript allow you to pass a function reference to a specific object's function, similar to what can be done in Java? Let's take a look at this code snippet: _.every(aS, function (value) { return exp.test(value); }); What if we want ...

How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object. The JSON object is fetched through the Relayr Javascript API, and looks like this: relayr.devices().getDeviceData({ token: tok ...

Showing information from an ajax Json onto a ul element within web forms using asp.net

My current challenge involves retrieving data from a database using JSON through this function: function BindMembers() { $.ajax({ url: "/test.asmx/test1", type: "GET", data ...

The require statement in Vue.js is failing to function dynamically

Having trouble dynamically requiring an image in Vue.js and it's not functioning as expected <div class="card" :style="{ background: 'url(' + require(image) + ')',}"> export default { data() { return { ...

Encountering a problem with the persistent JavaScript script

I have implemented a plugin/code from on my website: Upon visiting my website and scrolling down, you will notice that the right hand sidebar also scrolls seamlessly. However, when at the top of the screen, clicking on any links becomes impossible unless ...

The directive binding value is accurate, however it is failing to return a true result

The behavior of a custom directive is puzzling me. When I directly pass in a value, it works fine. However, if I bind the value to a variable, it doesn't work as expected. Interestingly, when I use console.log to show the value, it appears to be corre ...

Having trouble setting the locale in momentJS?

I have successfully integrated momentJS with Ionic/Angular using bower, and it is working well. However, when I try to change the locale to 'fr' or 'da', the output still remains in English even though I have the necessary locale files ...