package org.example.mongodbtest
import com.mongodb.BasicDBObject
import com.mongodb.MongoClient
import com.mongodb.client.MongoCollection
import com.mongodb.client.model.Filters.gt
import org.bson.Document
object DBTest {
@JvmStatic
fun main(args: Array<String>) {
val dbClient = MongoClient()
val db = dbClient.getDatabase("test")
val collection = db.getCollection("test")
val myDoc = collection.find(gt("x", 200)).first()
//insertDocument(collection)
//clearCollection(collection)
println("Collection Count: ${collection.count()}")
collection.find(BasicDBObject("x", 203)).forEach { println("Find Item: ${it.toJson()}") }
//println("First Document: ${if (myDoc?.toJson() != null) myDoc.toJson() else "No Document found"}")
}
fun clearCollection(collection: MongoCollection<Document>) {
collection.deleteMany(Document())
}
fun insertDocument(collection: MongoCollection<Document>) {
val doc = Document("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("info", Document("x", 203).append("y", 102))
collection.insertOne(doc)
}
}
package org.example.mongodbtest
import com.mongodb.BasicDBObjectimport com.mongodb.MongoClientimport com.mongodb.client.MongoCollectionimport org.bson.Document
object DBTest { @JvmStatic fun main(args: Array<String>) { val dbClient = MongoClient() val db = dbClient.getDatabase("test") val collection = db.getCollection("test") val myDoc = collection.find(gt("x", 200)).first()
//insertDocument(collection) //clearCollection(collection) println("Collection Count: ${collection.count()}") collection.find(BasicDBObject("x", 203)).forEach { println("Find Item: ${it.toJson()}") } //println("First Document: ${if (myDoc?.toJson() != null) myDoc.toJson() else "No Document found"}") }
fun clearCollection(collection: MongoCollection<Document>) { collection.deleteMany(Document()) }
fun insertDocument(collection: MongoCollection<Document>) { val doc = Document("name", "MongoDB") .append("type", "database") .append("count", 1) .append("info", Document("x", 203).append("y", 102))
collection.insertOne(doc) }}Does MongoDB support recursive queries with the Java API?
Hi Nick,
If you are intending to query for the document that you inserted from insertDocument(), where {info: {x: 230}} . What you are looking for is querying embedded document.
You can do this in MongoDB Java Driver either:
MongoCursor<Document> cursor = collection.find(eq("info.x", 203)).iterator();
Or, using Document class:
MongoCursor<Document> cursor = collection.find(new Document("info.x", 203)).iterator();
Note that the current stable version of the MongoDB Java driver is v3.3.
If the above doesn’t solve your issue, could you:
Regards,
Wan.