MongoDB get all documents, sort by a field and add ordering field based on the sorting - mongodb

I am trying to sort the result of my mongoDB query and add a ranking based on that sorting. Currently I only call .find().sort({total: 1}) and this gives me the correct ordering of the documents. But is it possible to "add a field" based on that sorting (basically a ranking field, starting from 1 and counting up)? I tried googling but didnt found anything that suits for this purpose.
Thanks in advance.

Related

View MongoDB array in order of indices with Compass

I am working on a database of Polish verbs and I'd like to find out how to display my results such that each verb conjugation appears in the following order: 1ps (1st person singular), 2ps, 3ps, 1ppl (1st person plural, etc.), 2ppl, 3ppl. It displays fine when I insert documents:
verb "żyć/przeżyć" conjugation as array and nested document
But when I go to perform queries it jumbles all the array elements up, in the first case (I want to see them in order of array indices), and sorts the nested document elements into alphabetical order (whereas I want to see them in the order in which they were inserted).
verb "żyć/przeżyć" conjugation array/document query
This should be an easy one to solve, I hope this comes across as a reasonable beginner's question. I have searched for answers but couldn't find much info on this topic. Any and all help is greatly appreciated!
Cheers,
LC.
Your screenshots highlight two different views in MongoDB Compass.
The Schema view is based on a sampling of multiple documents and the order of the fields displayed cannot be specified. The schema analysis (as at Compass 1.7) lists fields in case-insensitive alphabetical order with the _id field at the top. Since this is an aggregate schema view based on multiple documents, the ordering of fields is not expected to reflect individual document order.
If you want to work with individual documents and field ordering you need to use the Documents view, as per your second screenshot. In addition to displaying the actual documents, this view allows you to include sort and skip options for queries:

How to sort data using MongoDB Compass

I'm currently trying to use MongoDB Compass to query my collection. However, I seem to be only able to filter the data.
Is there any way for me to sort the data as well? I would like to sort my data in ascending order using one of my data fields.
If MongoDB Compass isn't the best way to order a collection, what other GUI could I use?
Using MongoDB Compass 1.7 or newer, you can sort (and project, skip, or limit) results by choosing the Documents tab and expanding the Options.
To sort in ascending order by a field myField, use { myField:1 }. Any of the usual cursor sort() options can be provided, including ordering results by multiple fields.
Note: options like sort and skip are not available in the default Schema tab because this view uses sampling to find a random set of documents, as opposed to the Documents view which displays a specific query result.

how to get the max value of a field in MongoDB

like:
{id:4563214321,updateTime:long("124354354")}
there are always new collections enter the db, so I would like to always get latest updated documents aka the largest update time. how to design the shell script? thanks in advance.
You can use a combination of limit and sort to achieve this goal.
db.collectionName.find({}).sort({"updateTime" : -1}).limit(1)
This will sort all of your fields based on update time and then only return the one largest value.
I would recommend adding an index to this field to improve performance.
This is a repeated question, you can find an answer in this link
Using findOne in mongodb to get element with max id
use like this,
db.collection.find().sort({updateTime:-1}).limit(1).pretty()
as findOne you can do it with this syntax:
db.collection.findOne({$query:{},$orderby:{_updateTime:-1}})

MongoDB Indexing and Projection

I have a few questions about MongoDB:
(1) Does indexing help with projection?
(2) I have assigned a collection a number of indexes and tried to run a find with sort, and then use explain, it shows BtreeCursor index on the sorted field.
Could it be that the other indexes have helped in the query part and explain just didn't show it because it shows only the last index that helped the find?
Or explain should show all indexes that assisted in querying, sorting, etc?
Thanks.
Does indexing helps in projection?
I believe the only time it will really help (defined by performance etc) is if the query is "covered": http://docs.mongodb.org/manual/tutorial/create-indexes-to-support-queries/
So for example, if you wanted to query on {d:1, e:2} and get back {_id, t, e}, you would do:
db.t.ensureIndex({d:1 , e:1, _id:1, t:1});
db.t.find({d:1, e:2}, {_id:1, t:1, e:1});
And that query's explain() output would show indexOnly as true meaning that it never loaded documents from disk to return a response.
So yes, indexes can help with projection under certain circumstances.
I have assigned a collection a number of indexes and tried to run a find with sort, and then use explain, it shows BtreeCursor index on the sorted field.
Yes it does.
Could it be that the other indexes have helped in the query part and explain just didn't show it because it shows only the last index that helped the find?
If you are a victim of index intersectioning then you would use an explain(true) to show all index plans that were used.
It is good to note that separate indexes are not used for find and sort with intersectioning, so the answer here is actually no: http://docs.mongodb.org/manual/core/index-intersection/#index-intersection-and-sort

The fastest way to show Documents with certain property first in MongoDB

I have collections with huge amount of Documents on which I need to do custom search with various different queries.
Each Document have boolean property. Let's call it "isInTop".
I need to show Documents which have this property first in all queries.
Yes. I can easy do sort in this field like:
.sort( { isInTop: -1 } );
And create proper index with field "isInTop" as last field in it. But this will be work slowly, as indexes in mongo works best with unique fields.
So is there is solution to show Documents with field "isInTop" on top of each query?
I see two solutions here.
First: set Documents wich need to be in top the _id from "future". As you know, ObjectId contains timestamp. So I can create ObjectId with timestamp from future and use natural order
Second: create separate collection for Ducuments wich need to be in top. And do queries in it first.
Is there is any other solutions for this problem? Which will work fater?
UPDATE
I have done this issue with sorting on custom field which represent rank.
Using the _id field trick you mention has the problem that at some point in time you will reach the special time, and you can't change the _id field (without inserting a new document and removing the old one).
Creating a special collection which just holds the ones you care about is probably the best option. It gives you the ability to logically (and to some extent, physically) separate the documents.
Newly introduced in mongodb there is also support for a "sparse" index which may fulfill your needs as well. You could only set the "isInTop" field when you want it to be special, and then create a sparse index on it which would not have the problems you would normally have with a single indexed boolean field (in btrees).