Mongodb set _id as a measure of reduction

I want to use mongodb default _id , but in descending order. I want to store messages and want to receive the latest messages at the beginning when I use find() . I use mongoose. I tried using

 postSchema.index({_id:-1}) 

but it did not work

 > db.posts.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mean-dev.posts" }] 

I reset the database and restarted mongod. No luck with that. Is there a way to set _id as a decreasing index in Sametime using the default mongodb index? I do not want to use sort() to sort the result according to _id descending _id .

+6
source share
2 answers

Short answer: No, you cannot create a descending index in the _id field. You also cannot delete it to recreate it as a descending index.

Long answer:

As indicated in the documentation, the MongoDB index in the _id field is automatically created as an ascending unique index, and you cannot delete it.

You also do not need to create an additional descending index in the _id field, because MongoDB can use the default index for sorting.

To make sure MongoDB uses an index to sort, you can use the explain command:

 db.coll.find().sort({_id : -1}).explain(); 

In the output explanation command, the corresponding part

 "cursor" : "BtreeCursor _id_ reverse" 

which means that MongoDB uses the index to sort your query in reverse order.

+6
source

you can actually use this index, just type .sort ({"_ id": - 1}) at the end of your query

ObjectId values ​​do not represent strict insertion order.

From the documentation: http://docs.mongodb.org/manual/reference/object-id/

IMPORTANT The relationship between the order of values ​​of ObjectId and the generation time is not strict for one second. If several systems or several processes or threads in one system generate values ​​within one second; ObjectId values ​​do not represent a strict insertion order. Skew between clients can also be a non-standard order even for values, since client drivers generate an ObjectId rather than a mongod process.

0
source

Source: https://habr.com/ru/post/971530/


All Articles