user9373173
user9373173

Reputation:

Swift 4: Sorting data with Firestore

I'm trying to pick the top 3 viewed meals of the day. Using this code i get incorrect details. So my structure is like this:

- meals 
   -- e.g Kebab
     --- view_count
     --- order_count
     --- like_count

My code:

let mealsRef = db.collection("meals").order(by: "view_count").limit(to: 3)

    // [START order_and_limit]
        mealsRef.getDocuments { (snap, err) in
            let dcs = snap!.documents
            for i in dcs {
                var data = i.data()
                print("meal => \(data["meal"] ?? ""), view_count => \(data["view_count"] ?? "")")
            }
    }

For testing proposes, I've increased the view_count by 300 - 200 - 100 on the Firebase console. But it returns three but incorrect ones.

Thank you all

Kim,

Upvotes: 0

Views: 783

Answers (1)

Tom
Tom

Reputation: 1359

The default order of Firestore is ascending. So you get the 3 meals with the least view_count. Try to take the order method with descending option:

func order(by field: String, descending: Bool) -> Query

Upvotes: 1

Related Questions