Order by date a result query


#1

Hi, there is a way to order the result of a query by a date field? Or I can do that only with the result array?

Version: 2.0 Build 16
Client OS: iOS 10.3
Server: -


#2

Have you looked at orderBy

Query .select(s)
                .from(DataSource.database(db))
                .where(w)
                .orderBy(Ordering.property("datefield").ascending())

#3

I don’t know why, when I try to insert the orderBy inside the query, the result of rows is zero, bug of couchbase lite?


#4

Are you sure you have the right property specified and it exists?


#5

Yes absolutely. If i use a property that doesn’t exist or if i don’t use .orderBy, rows contains the right values, but not ordered.


#6

What is the type of the date field?


#7

Is a string in RFC3339 format, like this: “yyyy-MM-dd’T’HH:mm:ssZZZZZ”


#8

This is the query:

SelectResult.all()
            )
            .from(
                DataSource.database(database!)
            )
            .where(
                Expression.meta().id.like("booking%").and(Expression.property("status").like("\(BookingStatus.Pending.rawValue)").or(Expression.property("status").like("\(BookingStatus.Accepted.rawValue)")))
            )
            .orderBy(
               Ordering.property("start_time").ascending()
        )

#9

Can you share a sample JSON document that you are trying to query. I suspect something in the structure that is not aligned with the query.

I just did a quick test by creating two documents with a Date field and ran a query and it worked as expected

  let prop1 = [
        "type": "test",
        "title" : "doc_101"
    ]
    
    let doc1 = Document(dictionary: prop1)
   
    doc1.setDate(Date(), forKey: "date")
    try? db.save(doc1)
    
    let prop2 = [
        "type": "test",
        "title" : "doc_102"
    ]
    
    let doc2 = Document(dictionary: prop2)
    doc2.setDate(Date(), forKey: "date")
    try? db.save(doc2)

My query :

 let searchQuery1 = Query.select(SelectResult.all())
        .from(
            DataSource.database(db)
        )
        .where(
            Expression.property("type").equalTo("test")
        )
        .orderBy(
            Ordering.property("date").ascending()
    )
    

sorts the results as expected!


#11

Fixed :slight_smile: thanks for your support!