CBLite 2.0.0DB22: how to query and update a document by a custom property (and not the ID)


When I know the document ID, I can do something like:

var document = database.GetDocument(id);
var mutable = document.ToMutable();

// set new data

// save document with new data

But how should I proceed when I want to query my document by a custom property (like a type or a custom identifier) and then update these documents?

using (var query = Query.Select(SelectResult.All())
    using(var rows = query.Execute())
        foreach (var row in rows)
            // at this point, how can I update a custom data for each row and save it?

In the code above I don’t know how to convert each row instance in a Document to set the data and save the instance again. Should I use thedatabase.GetDocument method for each row? Is there a better way to do this?


In your select statement, you will have to explicitly ask for SelectResult.Expression(Meta.ID) to get the document Ids of docs matching your query. The SelectResult.All() will not return meta data associated with the doc .

Once, you get the Id, you will have to fetch the document and update it similar to how you have in your code snippet above.


Thank you @priya.rajagopal

So I always will need to query the database twice: one to get the Ids and another to get the documents by Id, right?


If you don’t know the Id of document, you have to query for it . Once you get the Id, you then fetch the document , get a mutable copy of the document and then update.
BTW, you don’t have to do a select result.all() in your query. Once you get the document, you can use toDictionary or toMap to get the contents to update.

Can I change Query ResultSet and save the Document?


This is the first time I see this solution, I may have missed this point in the doc, if not, I think It will be great to add it.




Can you clarify what was not covered in the docs…
Is this what you are looking for ? https://developer.couchbase.com/documentation/mobile/2.0/couchbase-lite/swift.html#select-statement



Yes, it’ was exactly that, I completly missed this SelectResult.Expression(Meta.ID), thank you for pointing it out to me.

That’s good to know it’s in the doc.

I may have concentrated only on the examples, my bad.

But that’s good.

Thank you again.



No worries. There is a lot of content so easy to miss. Also for supplemental reading, there are a series of blog posts related to the query interface. I realized that probably not everyone is aware of those (maybe I should update the DB announcement?). Examples are in swift but you should be able to map to any other language.
Query Interface Basics
Full Text Search capabilities
query array collections
JOIN queries