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



有没有一种方法可以像MongoDB java驱动程序那样简单地检索查询字符串?例如:

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

迭代时,这应该调用查询:

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

它将被分批拆分,第一个将是101个元素,下一个最大为16MB(但我并不关心这个。我只需要初始查询(。有没有办法从mongodb java驱动程序的FindIterable或其他对象中检索这个字符串?

我在其他地方读到有人建议从伐木中做到这一点。我在运行时需要查询字符串,因为我必须使用它。

您可以在Java Driver v4.2和MongoDB v4.2.8中尝试这一点。您可以从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);

最新更新