How to save a document in one collection

I’m new to CB, I create a DB and saved few doc’s in the default collection of the database using this function

fun addStudent(studentName: String) {
        // Create a document
        val stdDocument = MutableDocument()
            .setString("type", "Student")
            .setString("studentName", studentName)

        // Save the document to the database
        try {
            database?.defaultCollection?.save(stdDocument)
            println("Student saved")
        } catch (e: CouchbaseLiteException) {
            e.printStackTrace()
        }
    }


but while retreving the data by using this query:

fun getSavedStudents(): ResultSet? {
        // Query for incomplete tasks
        val query = database?.defaultCollection?.let {
            QueryBuilder.select(SelectResult.all())
                .from(DataSource.collection(it))
                .where(
                    Expression.property("type").equalTo(Expression.string("Student"))
                )
        }

        return try {
            query?.execute()
        } catch (e: CouchbaseLiteException) {
            e.printStackTrace()
            null
        }
    }

im geting ResultSet, but after iterating the result set I’m not able to get the result I need to convert the each result to a list() or map() or JSON and have to fetch using the key “studentName”
here is the printed result to json string:
—> {“_default”:{“studentName”:“Praneeth”,“type”:“Student”}}
—> {“_default”:{“studentName”:“Praneeth”,“type”:“Student”}}
—> {“_default”:{“studentName”:“Praneeth”,“type”:“Student”}}
—> {“_default”:{“studentName”:“john”,“type”:“Student”}}
—> {“_default”:{“studentName”:“test”,“type”:“Student”}}
—> {“_default”:{“studentName”:“gani”,“type”:“Student”}}

why is this “_default” key is getting created

I’m not a cblite guy, but it seems that you should be able to produce a json object for each row/document and then reference the student as rowJson.get(“_default”)

Or project SELECT _default.* (or _default._default.* (?))

1 Like

The “_default” is the name of the default collection. When using “", the name of the quering collection will be used as the key to represent "”. You can rename the key by using “AS” such as SelectResult.all().as(“data”).

2 Likes

Thank you! so much, will try this. I saw few examples where they didnt use the “collection” instead they used to save the doc directly in db.save() and using a type key as an identifier for each doc

Thank you, for taking your time to reply. yeah I’m able to get the JSON, but I just want the response in a single JSON array with JSON objects instead I’m getting each element as a separate JSON array

The Database’s save() API is the same as using default Collection’s save(). Also the Database’s save() is deprected so it’s recommended to use Collection’s save() method.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.