0

How sort the documents in a collection randomly.

This is the function I use to get the documents, how can I sort them randomly?

func fetchExplore() {
    let query = COLLECTION_POSTS.limit(to: 6)
    
    if let last = lastDoc {
        let next = query.start(afterDocument: last)
        next.getDocuments { snapshot, _ in
            guard let documents = snapshot?.documents, !documents.isEmpty else { return }
            self.lastDoc = snapshot?.documents.last
            self.posts.append(contentsOf: documents.compactMap({ try? $0.data(as: Post.self) }))
        }
    } else {
        query.getDocuments { snapshot, _ in
            guard let documents = snapshot?.documents else { return }
            self.posts = documents.compactMap({ try? $0.data(as: Post.self) })
            self.lastDoc = snapshot?.documents.last
        }
    }
    print("DEBUG: did fetch posts Explore")
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Are you looking to get a random set of documents from the collection? If so, see https://stackoverflow.com/questions/46798981/firestore-how-to-get-random-documents-in-a-collection – Frank van Puffelen Jun 19 '21 at 16:36
  • Hi thanks, I tried to do that but I don't really understand how to create the "random" property. You know what I have to do? please – Santiago Padilla Jun 21 '21 at 17:38
  • Are you asking [how to generate a random value in Swift?](https://stackoverflow.com/search?q=%5Bswift%5D+how+to+generate+a+random+value) – Frank van Puffelen Jun 21 '21 at 18:35

1 Answers1

0

This is normally resolved by adding either one or two float numbers that you can start a query with, such as: myDocsRef.whereField("random", isGreaterThanOrEqualTo: randomNumber).limit(1)

This answer covers it in depth: Firestore: How to get random documents in a collection

DIGI Byte
  • 4,225
  • 1
  • 12
  • 20
  • Hi thanks, I tried to do that but I don't really understand how to create the "random" property. You know what I have to do? please – Santiago Padilla Jun 21 '21 at 17:38
  • When you create the document from the client - you call the random function for your language and set it to 'random' - Swift `Float.random(in: 1..<1)` or `CGFloat(arc4random()) / CGFloat(UInt32.max)` - refer here for more https://stackoverflow.com/a/28075467/2301161 – DIGI Byte Jun 21 '21 at 21:08