Mongo add document in the middle of collection - javascript

When I insertOne() document in the collection Mongo add the document between the first and last document.
It is expected to be added at the end, right? But for me ideally would be to add the document at the beginning, for example as .unshift() JS works.
I'm building Blog so new posts should be added at the top of the list.
But I can always .reverse() of course .
Main problem is why document is added in the middle.

You should sort the collection by creation time(when you are trying to output them sorted by creation time) rather than trying to change to order of insertions in the collections.
db.posts.find().sort({creation_time: -1})
This way the recent entries will come out on top.
Ref: https://docs.mongodb.com/manual/reference/method/cursor.sort/#cursor.sort

Related

How to remove all items of a Mongo collection

I have seen that to remove all items of a Mongo collection using JavaScript I should use :
DockerStats.remove(); //where DockerStats is my collection
So my goal is to purge the DB every 20sec so I did the following code :
setInterval(Meteor.bindEnvironment(function(){
DockerStats.remove();
console.log("ok")
}),20000);
But when I start the app I had +/- 1000items then despite the terminal wrote 2 times "ok" I still have more than 1000items so it doesn't work because even if I check right after the "ok" I have more than 1000items and the number is always growing up.
So maybe I'm removing the items with the wrong way ?
According to the docs, you need to pass in an empty object to delete the whole collection. So, the below would remove all students from the Students collection:
Students.remove({})
I think this is because if you want to remove everything and start over you would use the drop method and recreate it, which the docs says is more performant.

mongo cursor findOne

I'm trying to open a stream of data from mongoDB by querying a field with an array of values, and return only one record per index of array.
var cursor = Collection.findOne({'lastName': { $in: [arrayOfLastNames]}}).cursor();
cursor.on('data', function (record) {
//do something with record
})
for whatever reason, it is pulling multiple records per index of arrayOfLastNames. The .findOne() method is behaving as .find() would.
Any suggestions as to why this is happening, or possible alternatives to this implementation would be greatly appreciated.
You're running into issues because you used a cursor. From the mongoDB documentation, "You cannot apply cursor methods to the result of findOne() because a single document is returned."
From your comment, you want to call findOne once for every item in the array since $in with findOne will find the first document according to the "natural order" of the document that matches any item in the array (you might also consider just using a general find honestly, since then your cursor solution will work).

Meteor - loop through Collection to delete the first x-many items

I have an FS Collection in Meteor called "MyUploads". I will be performing some functionality on the files uploaded into the Collection, and then additional files will be created and subsequently added within MyUploads. I have created an event, in which this will take place, called #parseUploads. Within the event, and prior to the addition of the subsequent files added to MyUploads, I have created a variable:
var previousCount = fileCount;
which is responsible for storing the original count of documents that the user had added to the Collection. Then, the parsing function will perform on each of these documents, and add the newly parsed documents to the collection.
My question is: How do I loop through the Collection from the first document up through the previousCount's value document?
In other words, if the previousCount has a value of 3 (meaning, that the user had uploaded 3 documents), then after the parsing functionality has been performed, there will be 3 subsequent documents added to the collection. I then would like to know how I can loop through the Collection and delete only the first 3 documents, while leaving the 3 subsequent documents remaining in the Collection.
I would recommend adding a boolean field to the collection to act as a flag to denote parsed items. Once an item is parsed, you can update it.
Then you can remove items from the collection based on the presence of that flag.
MyCollection.remove({stale: true});
Hope that helps,
Elliott

mongodb find in order of last record to first

My project inserts a large number of historical data documents into a history collection, since they are never modified the order is correct (as no updating goes on) but backwards for retrieving.
I'm using something like this to retrieve the data in pages of 20 records.
var page = 2;
hStats_collection.find({name:name},{_id:0, name:0}).limit(20).skip(page*20).toArray( function(err, doc) {
});
After reading my eyes dry, $sort is no good, and it appears the best way to reverse the order that the above code retrieves is to add an index via a time stamp element in the document, of which I already have a useful item called started (seconds since epoc) and need to create an index for it.
http://docs.mongodb.org/manual/tutorial/create-an-index/
The docs say I can do something like:
hStats_collection.createIndex( { started: -1 } )
How do I change my .find() code above to find name and reference the started index so the results come back newest to oldest (as oposed to the natural find() oldest to newest).
hStats_collection.find({name:name},{_id:0, name:0}).sort({ started:-1 }).limit(20).

Mongo DB reorder objects on insert

In my node js app Im using Mongo DB , and I have an Issue when Inserting something in database. When I add new record to collection objects beign reordered . Does anyone knows why is this happening ? Im doing insert like this
collection.insert(object, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred'});
} else {
// Error
}
});
Actually , any operation on collection change the order of objects , does anyone knows why is this happening ?
MongoDB documents have padding space that is used for updates. If you make small changes to a document like adding/updating a small field there is a good chance that the size of the updated document will increase but will still fit into allocated space because it can use that padding. If the updated document does not fit in that space Mongo will move it to a new place on disk. Thus your documents might move a lot in the beginning until Mongo learns how much padding you would usually need to prevent such moves. You can also set higher padding to avoid documents being moved in the first place.
In either case you can't really rely on the insertion order to get sorted list of documents. If you want guaranteed order you need to sort. In your case you can sort by _id because it's a monotonically increasing counter which contains date and time details:
// in the order of insertion unless you got `_id` value externally
// (in your code, not auto assigned by Mongo) and doc with such ID
// was inserted much later.
// Sharding might also introduce tiny ordering mismatches
db.collection.find().sort( { '_id': 1 } );
// most recently inserted items first
db.collection.find().sort( { '_id': -1 } );
If you use capped collection the order of inserts will be preserved always, i.e. Mongo will never move documents. In that case you can use natural order sorting:
db.collection.find().sort( { $natural: 1 } )
which is equivalent to sorting by _id as shown above.
Do not use natural order sorting with non-capped collections (regular collections) because it will not be reliable in presence of updates.

Categories

Resources