Search code examples
javamongodbmongodb-querydriver

How to retrieve Mongo query string from FindIterable (mongo java driver)


Is there a way to simply retrieve the query string that MongoDB java driver does? For example:

filter = eq("field","value");

FindIterable<BasicDBObject> find = collection.find(filter).projection(fields(include("field"), excludeId()));

When iterating, this should invoke the query :

db.collection.find({"field":"value"},{"field":1, "_id":0})

which will be split in batches, the first of which will be of 101 elements and next ones of max 16MB (but I don't really care about this. I just need the initial query). Is there a way to retrieve this string from the FindIterable or other objects of mongodb java driver?

I read elsewhere of people who were suggesting to do it from logging. I need the query string at runtime cause I have to use it.


Solution

  • You can try this with the Java Driver v4.2 and MongoDB v4.2.8. You can get the filter and projection from the Bson as JSON string values.

        MongoCollection<Document> coll = client.getDatabase("test").getCollection("books");
        Bson filter = eq("author", "Mark Twain");
        String filterJson = filter.toBsonDocument(BsonDocument.class, Bson.DEFAULT_CODEC_REGISTRY).toJson();
        System.out.println(filterJson);    // {"author": "Mark Twain"}
        Bson projectn = fields(include("title"), excludeId());
        String projectJson = projectn.toBsonDocument(Document.class, Bson.DEFAULT_CODEC_REGISTRY).toJson();
        System.out.println(projectJson);    // {"title": 1, "_id": 0}
        coll.find(filter).projection(projectn);