0

Using Java I create a complex MongoDB query and before execute it usually I log the query:

log.info("Filter: {}", queryFilter);

The log is usefull but the queryFilter is printed is this form:

And Filter{filters=[Filter{fieldName='FinInstrmGnlAttrbts.ClssfctnTp', value=RFBTCB}, [...] ]}

I would like to log the query in "Javascript form" in the same way it should execute directly into MongoDB, like:

{$and : [ {'FinInstrmGnlAttrbts.ClssfctnTp' : 'RFBTCB'}, [...] ]}

In this way, if a day an error will occur I can take directly the query from the log and test it in MongoDB, without retype the entire query manually.

Is it possible in any way?

Michele
  • 1,213
  • 2
  • 18
  • 36
  • I haven't used it but taking a peek at the API docs (version 3.5, latest) and guessing the type of `queryFilter` to be `BasicDBObject` I see that there's a [toJson](http://mongodb.github.io/mongo-java-driver/3.5/javadoc/com/mongodb/BasicDBObject.html#toJson--) method. Right now you're getting the results of the `toString` method. What happens if you log `queryFilter.toJson()` instead? – David Conrad Feb 08 '18 at 08:48
  • `queryFilter` is a `org.bson.conversions.Bson` object and it hasn't a `toJson` method. – Michele Feb 08 '18 at 09:49
  • Are you sure? That's not a concrete type, that's an interface. Try calling `getClass()` on it to find out what it really is, then cast it to its concrete type. – David Conrad Feb 08 '18 at 10:16
  • I can't cast it because my `queryFilter` is a `com.mongodb.client.model.Filters.AndFilter` and this class is private. And in a more general way I couldn't cast it because I couldn't know how the `queryFilter` was composed (it could be an `AndFilter` or an `OrFilter` or ...) – Michele Feb 09 '18 at 09:30
  • Ah, gotcha. Glad you found a solution. – David Conrad Feb 10 '18 at 01:19

1 Answers1

1

I've resolved with

BsonDocument bsonDocument = queryFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
log.info("Filter: {}", bsonDocument);
Michele
  • 1,213
  • 2
  • 18
  • 36