You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何从FireStore按顺序查询单个指定字段数据?

Fixing Firestore Query to Get Single Usernames in Order

Let's break down what's happening in your code and how to adjust it to get single usernames in the sorted order you want.

The Issue in Your Current Code

Right now, you're looping through every document in your snapshot (limited to 5), and for each document, you're converting it to a UsersData instance and printing its name. That's why you see multiple names in your output—you're printing one per document in the query result.

Solution 1: Get Just the Top Leader's Username

If you only need the single top user (sorted by BOOKS_Field descending), skip the loop and directly access the first document in the snapshot:

func getLeadersfromServer() {
    let leaderRef = db.collection("USERS_Collection").order(by: "BOOKS_Field", descending: true).limit(to: 5)
    leaderRef.addSnapshotListener { (snapShot, error) in
        if let error = error {
            print(error)
        } else {
            // Check if there are any documents available
            guard let topDocument = snapShot?.documents.first else {
                print("No users found in leaderboard")
                return
            }
            
            // Convert the top document to your UsersData model
            if let topUser = UsersData(dictionary: topDocument.data()) {
                print("Top Leader: \(topUser.NAME_FIELD)")
                // Store this username in a variable or use it directly here
            } else {
                print("Failed to parse top user data")
            }
        }
    }
}

Solution 2: Collect All Sorted Usernames to Access Individually

If you want to keep all 5 sorted usernames and access them one by one (e.g., first, second, third place), collect them into an array first:

func getLeadersfromServer() {
    let leaderRef = db.collection("USERS_Collection").order(by: "BOOKS_Field", descending: true).limit(to: 5)
    leaderRef.addSnapshotListener { (snapShot, error) in
        if let error = error {
            print(error)
        } else {
            var sortedUsernames: [String] = []
            
            // Loop through documents and build the sorted list
            for document in snapShot?.documents ?? [] {
                if let user = UsersData(dictionary: document.data()) {
                    sortedUsernames.append(user.NAME_FIELD)
                }
            }
            
            // Now access single usernames in order
            if let firstPlace = sortedUsernames.first {
                print("1st Place: \(firstPlace)")
            }
            if sortedUsernames.count >= 2 {
                print("2nd Place: \(sortedUsernames[1])")
            }
            // Repeat for indices 2, 3, 4 as needed
        }
    }
}

Quick Note on Snapshot Listeners

If you only need to fetch the data once (not listen for real-time updates), replace addSnapshotListener with getDocuments(completion:) instead.

内容的提问来源于stack exchange,提问作者Tom B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:33:46