How to use $redact by using MongoDB Java Driver 3.5.

47 views
Skip to first unread message

aniket patil

unread,
Oct 26, 2017, 6:18:36 PM10/26/17
to mongodb-user
I am using MongoDB 3.4 and MongoDB Java Driver 3.5. I don't find any way to implement $redact in java. Also I don't find anyway to implement it via MongoTemplate. 
I have implemented it by using getDB method but the method getDB(String) from the type Mongo is deprecated. Please refer following code.

 List<Serializable>redactCondition = Arrays.asList(new BasicDBObject("$or",redactList),"$$DESCEND","$$PRUNE");
 DBObject redact = new BasicDBObject("$redact",new BasicDBObject("$cond",redactCondition));

Kevin Adistambha

unread,
Nov 2, 2017, 1:29:36 AM11/2/17
to mongodb-user

Hi Aniket

You can use the Document.parse() method to create a Document instance from a JSON string: http://mongodb.github.io/mongo-java-driver/3.5/javadoc/org/bson/Document.html#parse-java.lang.String-

For example, this Java snippet follows the example in the $redact page and will produce the same output:

MongoIterable<Document> agg = collection.aggregate(
    Arrays.asList(
        Document.parse("{$match: {'year': 2014}}"),
        Document.parse("{ $redact: {" +
            "$cond: {" +
            "if: { $gt: [ { $size: { $setIntersection: [ '$tags', ['STLW', 'G'] ] } }, 0 ] }," +
            "then: '$$DESCEND'," +
            "else: '$$PRUNE'" +
            "}}}")
    )
);

Best regards
Kevin

Reply all
Reply to author
Forward
0 new messages