How to do full-text search with MongoDB Mobile Android?

17 views
Skip to first unread message

Percula

unread,
Jun 12, 2019, 12:30:04 PM6/12/19
to MongoDB Stitch Users
I created a sample app to try out MongoDB Mobile, but I cannot figure out how to query. There doesn't appear to be any documentation specific to Android in this regard (if there is, please share!). Currently, the following code will check "overview.name" for an exact match equal to "test". But I'd like to do a full-text search so that something like "this is a test name" or "Test name" would also match. Thanks for your help!

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val fileName = "sample.json"
val sampleData = application.assets.open(fileName).bufferedReader().use{ it.readText() }

val doc = Document.parse(sampleData)
val rawObjects = doc.getValue("assets")

val documentsMap = rawObjects
?.asList<Map<String, Any?>>()
?.filter { it.isNotEmpty() }
?: java.util.ArrayList()

// Create the default Stitch Client
val client = Stitch.initializeDefaultAppClient("testmongodb-qopzy")

// Create a Client for MongoDB Mobile (initializing MongoDB Mobile)
val mobileClient = client.getServiceClient(LocalMongoDbService.clientFactory)

// Point to the target collection and insert a document
val localCollection = mobileClient.getDatabase("my_db").getCollection("assets")

val startInsert = System.nanoTime()
localCollection.insertMany(documentsMap.map { Document(it) })
val endInsert = System.nanoTime()

//Find all documents that match the find criteria
val query = Document()
query.put("overview.name", BsonString("test"))

val startQuery = System.nanoTime()
val cursor = localCollection.find(query)
val results = cursor.into(ArrayList<Document>()) as ArrayList<Document>
val endQuery = System.nanoTime()
Log.v("Results: ", results.toString())
Log.v("Insert duration: ", (startInsert - endInsert).toString())
Log.v("Query duration: ", (startQuery - endQuery).toString())
}

}
Reply all
Reply to author
Forward
0 new messages