• Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

141
Views
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.

11 months ago · Santiago Trujillo
1 answers
Answer question

0

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);
11 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.