Does MongoDB find() query return documents sorted by creation time?

Since ObjectID saves timestamp by default, we can use it to get documents sorted by creation time with CollectionName.find().sort({_id: 1}).

Also, I noticed that regular CollectionName.find() query always returns the documents in same order as CollectionName.find().sort({_id: 1}).

My question is:

Is CollectionName.find() guaranteed to return documents in same order as CollectionName.find().sort({_id: 1}) so I could leave sorting out?

Best How To :

No. Well, not exactly. A db.collection.find() will give you the documents in the order they appear in the datafiles host of the times, though this isn't guaranteed.

Result Ordering

Unless you specify the sort() method or use the $near operator, MongoDB does not guarantee the order of query results.

As long as your data files are relatively new and few updates happen, the documents might (and most of the times will) be returned in what appears to be sorted by _id since ObjectId is monotonically increasing.

Later in the lifecycle, old documents may have been moved from their old position (because they increased in size and documents are never partitioned) and new ones are written in the place formerly occupied by another document. In this case, a newer document may be returned in a position between two old documents.

There is nothing wrong with sorting documents by _id, since the index will be used for that, adding only some latency for document retrieval.

However, I would strongly recommend against using the ObjectId for date operations for several reasons:

ObjectIds can not be used for date comparison queries. So you couldn't query for all documents created between date x and date y. To archive that, you'd have to load all documents, extract the date from the ObjectId and compare it – which is extremely inefficient.

If the creation date matters, it should be explicitly addressable in the documents

I see ObjectIds as a choice of last resort for the _id field and tend to use other values (compound on occasions) as _ids, since the field is indexed by default and it is very likely that one can save precious RAM by using a more meaningful value as id.

The answer is no, tables won't be locked, database won't be down. But, if your database is large and it takes long time to backup it, you can sometimes expect performance degradation(slow SQL queries from your application).

The key here is to step back and think about the problem from another angle. You are duplicating lots of code because you are creating instances of the database and command classes within the method. So inject them instead: public class SomeDBClass { static DataTable exec_DT(DBConnection conn, DBCommand cmd) {...

Your problem here is that you have missed one of the core concepts of how mapReduce works. The relevant documentation that explains this is found here: MongoDB can invoke the reduce function more than once for the same key. In this case, the previous output from the reduce function for...

In an object oriented language, would you make a class for every user? Or would you have an instance of a class for each user? Having one table per user is a really bad design. You can't search messages based on any field that isn't the username. With your current...

Meteor's collection API is somewhat different from that of the mongo API. find takes up to two parameters: a selector object, and an options object. options allows you to specify such things as sort, skip, limit and fields, in addition to the meteor-specific reactive and transform.

Why don't you just do it in one single query? Just replace the necessary table and column name, and variables/values/parameters to be bind in your query: $query = mysqli_query($conn, "SELECT first_name, last_name, description, role FROM `wp_usermeta` WHERE `first_name` = '$first_name' OR `last_name` = '$last_name' OR `description` = '$description' OR `role`...

typically, you would store the password as some sort of encrypted hash. It is best if this is one-way, so it cannot be decrypted. When authenticating, you check that you can generate the same hash from the provided password; not decypt what is stored. Your hash should also be "salted"...

Redis would probably be fastest, especially if you don't need a durability guarantee - most of the game can be played out using Redis' in-memory datastore, which is probably gonna be faster than writing to any disk in the world. Perhaps periodically, you can write the "entire game" to disk....

That's a pretty wide question, partly opinion based. This question should be closed, but I still want to give you some advice. There once was the Active Record pattern, which has been proven to be pretty difficult to maintain. The solution was the DAO pattern, but this adds a lot...

$set is not an array update operation. The $set operator replaces the value of a field with the specified value. You just want to use $push by itself, as in .update({_id: id}, {$push: {name: item}}) You can't interpolate object property names in raw object declarations, so if you want to...

It seems to be Windows UAC reliant. As our application run in compatibility mode, UAC visualization is active and causing may some problems. The reason for this is, that the COBOL databse is a file based database, and the client where are coding for uses these files in ODBC DSN...

The amount of time it takes to add the index would depend on your hardware, but with 20206 records a simple index as you describe shouldn't take very long for most hardware. Queries fully covered by the index (i.e. where you specify A and B, or just A, but not...

Well, Both the actions actually means update, where PUT is full update and PATCH is partial update. In case of PUT you already know the identifier of the resource and the resource already exists, so it is not a create and delete action per se. Infact, you can make do...

Yes, this is the expected behavior. Since the MapReduceIterable is a fluent interface, there must be some way to signal the driver that it's time to actually do the map-reduce, and currently the only way to do that is to start iterating. If you really don't need the results, and...

The method you're looking for is QSqlQuery::lastInsertId(). To quote the documentation: Returns the object ID of the most recent inserted row if the database supports it. An invalid QVariant will be returned if the query did not insert any value or if the database does not report the id back....

When you call an async method you should await the returned task, which you can only do in an async method, etc. Awaiting the task makes sure you continue execution only after the operation completed, otherwise the operation and the code after it would run concurrently. So your code should...

When you create an instance of the Post model, you need to assign the _id from the user as an ObjectId, not a string: var ObjectId = require('mongoose').Types.ObjectId; Post.create({ text: 'farheen123', created_by: new ObjectId('5587bb520462367a17f242d2') }, function(err, post) { if(err) console.log("Farheen has got error"+err); else console.log(post); }); ...

Insert only accepts a final document or an array of documents, and an optional object which contains additional options for the collection. db.collection.insert( <document or array of documents>, { // options writeConcern: <document>, ordered: <boolean> } ) You may want to add the _id to the document in advance, but...

Yes, Changes made to data in MongoDB shell are permanent but for configuration parameters, they will last only till next restart of instance if they are not specified in config file. MongoDB runs with default values if config file is not specified. You can specify config file as, mongod --config...

To ensure data is available, you can make a refresh request to corresponding index before GET/SEARCH: http://localhost:9200/your_index/_refresh Or refresh all indexes: http://localhost:9200/_refresh ...

Attention: Mongo id should be unique as possible in order to scale well. The default ObjectId is consist of a timestamp, machine ID, process ID and a random incrementing value. Leaving it with only the latter would make it collision prone. However, sometimes you badly want to prettify the never-ending...

The only way to do this is to manually run a count(*) on all of your tables filtering on the particular date field. The reason for this is because one table might have a column "CreatedDate" that you need to check if it's >30 days old, while another might have...

Oracle uses "logical" und "physical" structures to store the data. For this case: The extents of a segment can be stored in different datafiles, so just summing up can work but must not work see here: http://docs.oracle.com/cd/E11882_01/server.112/e40540/logical.htm#CNCPT301 Plus: Oracle has a "High Water Mark" so even if your segment size...

It's not "documents" it's "Objects" as is stated, but you would not be the first person to not fully understand the .explain() output. Put simply, you have as part of your index an "array" element (actually the maximum "two" allowed), which means that your index is what we call "MultiKey"....

Try this SELECT count(receiver_id) as total_receiver FROM gr_group_memberships INNER JOIN gr_group on gr_group_memberships.group_id = gr_group.id GROUP BY gr_group_memberships.receiver_id ORDER BY gr_group_memberships.receiver_id DESC I think it will worked what you want...

If you are looking to find the records matching with both the criteria here is a way of doing it select `item_id` FROM `item_meta` where ( `meta_key` = 'category' and `meta_value` = 'Bungalow' ) or ( `meta_key` = 'location' AND `meta_value` = 'Lagos' ) group by `item_id` having count(*)=2 ...

The Cognos _days_between function works with dates, not with datetimes. Some databases, like Oracle, store all dates with a timestamp. On a query directly to the datasource, try using the database's functions to get this data instead. When possible, this is always preferable as it pushes work to the database,...

In barely any case would you get direct access to another company's database, even if you are affiliated. The most common way would be an API (which might be public or licensed): https://en.wikipedia.org/wiki/Application_programming_interface If the data is publicly available on a website, some do content parsing although this is not...

Though this is possible to do with some real wrangling you would be best off changing the document structure to "flatten" the array entries into a single array. The main reason for this is "updates" which are not atomically supported by MongoDB with respect to updating the "inner" array due...