Swift中如何从FireStore按顺序查询单个指定字段数据?
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.

