简体   繁体   English

如何从 FindIterable 中检索 Mongo 查询字符串(mongo java 驱动程序)

[英]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?有没有办法简单地检索 MongoDB java 驱动程序所做的查询字符串? 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).它将分批拆分,其中第一个将是 101 个元素,接下来是最大 16MB 的元素(但我并不真正关心这一点。我只需要初始查询)。 Is there a way to retrieve this string from the FindIterable or other objects of mongodb java driver?有没有办法从 FindIterable 或 mongodb java 驱动程序的其他对象中检索此字符串?

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.我在运行时需要查询字符串,因为我必须使用它。

You can try this with the Java Driver v4.2 and MongoDB v4.2.8.您可以使用 Java 驱动程序 v4.2 和 MongoDB v4.2.8 进行尝试。 You can get the filter and projection from the Bson as JSON string values.您可以从Bson获取过滤器和投影作为 JSON 字符串值。

    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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM