Sort documents in firestore collection chronologically - flutter

Is there a way to sort documents in collection chronologically when they are created? Currently, they are all over the place. For example, in To-Do app, when you add new item to collection, it should display at the bottom, last, not somewhere in the middle.

You will need to define an order based on some data in the document, and order your queries based on that field.
The typical solution for time-base order to make sure your documents all contain a timestamp field that you can use to sort them. When you call add() (or other methods to update data), you can tell Firestore to use the current time using FieldValue.serverTimestamp():
collection(...).add({
..., // your other fields
createdOn: FieldValue.serverTimestamp()
})
Then you can use that field to sort when querying with orderBy():
collection(...).orderBy('createdOn')

Try using DateTime.now() for the document ID. This should put the collection in chronological order.
For example:
Firestore.instance.collection('Posts').document(DateTime.now().toString()).setData({});

Related

How to sort firestore document id date wise firebase flutter

I am importing csv data to firestore by parsing it. The csv is making documents randomly without following the date's chronological order e.g 2019's data first and 2022 or latest data at last. I want to show the data chronological wise on the app side or even if possible on the javascript side of firebase while parsing I'm ready to make changes.
Format is dd-mm-yyyy I've tried orderBy but it didn't worked.
Note that there's Date field as well in my every document and I can't use Timestamp cause data is coming from csv.
I'm attaching image of my app and firestore document id and collection to get an better idea of what I want to achieve.
Document IDs are strings, so they use lexicographical sort order. If you want them to also be sorted chronologically, you should use a date format that fits those needs. For example ISO-8601: 2022-09-15. In this format, ordering by document ID will put the documents in the order of the date.

Flutter project Firestore data sorting

I have some data on my project firestore. It seems like this:
I am trying to sort this data by SKU. As you can see it is in a list. How can I give its field path to orderBy() method?
There is no way to sort the document you've shown on a SKU value, since that value exists in an array field and there could be multiple values.
If you want to sort on a specific SKU value, add a top-level field (e.g. skuForOrdering) to the document and sort on that with orderBy('skuForOrdering').

Firestore order by time but sort by ID

I have been trying to figure out a way to query a list of documents where I have a range filter on one field and order by another field which of course isn't possible, see my other question: Order by timestamp with range filter on different field Swift Firestore
But is it possible to save documents with the timestamp as id and then it would sort by default? Or maybe hardcode an ID, then retrieve the last created document id and increase id by one for the next post to be uploaded?
This shows how the documents is ordered in the collection
Any ideas how to store documents so they are ordered by created at in the collection?
It will order by document ID (ascending) by default in Swift.
You can use .order(by: '__id__') but the better/documented way is with FieldPath documentID() I don't really know Swift but I assume that it's something like...
.order(by: FirebaseFirestore.FieldPath.documentID())
JavaScript too has an internal variable which simply returns __id__.
.orderBy(firebase.firestore.FieldPath.documentId())
Interestingly enough __name__ also works, but that sorts the whole path, including the collection name (and also the id of course).
If I correctly understood your need, by doing the following you should get the correct order:
For each document, add a specific field of type number, called for example sortNbr and assign as value a timestamp you calculate (e.g. the epoch time, see Get Unix Epoch Time in Swift)
Then build a query sorted on this field value, like:
let docRef = db.collection("xxxx")
docRef.order(by: "sortNbr")
See the doc here: https://firebase.google.com/docs/firestore/query-data/order-limit-data
Yes, you can do this.
By default, a query retrieves all documents that satisfy the query in
ascending order by document ID.
See the docs here: https://firebase.google.com/docs/firestore/query-data/order-limit-data
So if you find a way to use a timestamp or other primary key value where the ascending lexicographical ordering is what you want, you can filter by any fields and still have the results sorted by the primary key, ascending.
Be careful to zero-pad your numbers to the maximum precision if using a numeric key like seconds since epoch or an integer sequence. 10 is lexicographical less than 2, but 10 is greater than 02.
Using ISO formatted YYYY-mm-ddTHH:MM:SS date-time strings would work, because they sort naturally in ascending order.
The order of the documents shown in the Firebase console is mostly irrelevant to the functioning of your code that uses Firestore. The console is just for browsing data, and that sorting scheme makes it relatively intuitive to find a document you might be looking for, if you know its ID. You can't change this sort order in the console.
Your code is obviously going to have other requirements, and those requirements should be coded into your queries, without regarding any sort order you see in the dashboard. If you want time-based ordering of your documents, you'll have to store some sort of timestamp field in the document, and use that for ordering. I don't recommend using the timestamp as the ID of a document, as that could cause problems for you in the future.

Mongodb query which avoid duplicates items with different _id

I'm working with dump of events provided by 3rd party side. And in this dump they have duplicates events, which is fully identical, but have different _id. So my goal is to provide unique only data, so I can't use duplicates event.
Is it possible to build the query which return me only documents with unique value?
Lets say, in each document i have EventId field, and I need all the events, with unique EventID
I can't change dump, have only read permission to it.
You can use db.collection.distinct() method http://docs.mongodb.org/manual/reference/method/db.collection.distinct/

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).